<?php

namespace app\admin\controller;

use app\admin\model\Order;
use app\BaseController;
use app\dic\DicOrder;
use app\dic\DicPublic;
use app\dic\DicSite;
use think\facade\Db;
use think\App;

/**
 * @author xjw
 * @class:Taskorder 定时任务=>订单操作
 * @method order 订单操作
 * @method deal_orders 处理订单
 * @method update_order_lastmonth 更新订单=>商品详情以及遍体数据=>算业绩
 * @method update_order_4month 更新订单=>统计销量
 * @method update_order_3day 更新三天订单=>统计订单量
 * @method update_purchase_cost 更新采购成本
 * @return  
 */


class Taskorder extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new Order();
    }

    /**
     * 
     *  订单操作   
     *  type=3 获取订单  5分钟执行一次  每小时第四十五分钟执行
     *  type=2 更新订单  15分钟执行一次
     */
    //TODO::每小时第四十五分钟执行
    //TODO::定时任务的时间都为1分钟
    public function  order()
    {
        $type = input('type');
        if (!$type) {
            return error('type不能为空');
        }
        $site_id = input('site_id');
        $where = [
            'site_type' => DicSite::$site_type_1,
            'status' => DicSite::$status_normal,
        ];
        if (!empty($site_id)) {
            $where['id'] = $site_id;
            $site = table('site')->where($where)->find();
        } else {
            $site = table('site')->where($where)->order(['task_updatetime_product' => 'asc'])->find();
        }
        $return = $this->deal_orders($site, $type);
        return success('操作成功', $return);
    }

    /**
     * 处理订单=>更新order表和site.updatetime_order字段
     *   获取订单  时间条件 site.updatetime_order
     *   更新订单  时间条件 order.ycreated_at
     */

    public function deal_orders($site, $type)
    // public function deal_orders()
    {
        $url = $site['site_url'] . "/admin/api/2023-07/orders.json";
        if ($type == DicOrder::$type_3) {
            if (!empty($site['updatetime_order'])) {
                $created_at_max = $site['updatetime_order'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', time());
                $created_at_max2 = date('H:i:s', time());
                $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
            }
            $url = $url . '?created_at_max=' . $created_at_max;
        }
        if ($type == DicOrder::$type_2) {
            $last_order = table('order')
                ->where('site_id', $site['id'])
                ->order('ycreated_at desc')
                ->find();
            if ($last_order) {
                $updated_at_min = $last_order['ycreated_at'];
                $updated_at_mins = explode('T', $updated_at_min);
                $updated_at_mins[0] = date('Y-m-d', strtotime("$updated_at_mins[0]-1day"));
                $updated_at_min = $updated_at_mins[0] . 'T' . $updated_at_mins[1];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2021-07-01T00:00:00-04:00';
            }
            $url = $url . '?created_at_min=' . $updated_at_min;
        }
        $url = $url . '&status=' . DicOrder::$status_any . '&limit=' . DicPublic::$task_limit_100 . '&financial_status=' . DicOrder::$financial_status_any;
        // halt($url);
        $data =  geturl($url, $site['apikey'], $site['apisecret']);
        if ($data) {
            $update_ordertime_data_errors = $data;
            $data = json_decode($data, true);
            // halt($data);
            if (!empty($data['errors'])) {
                $update_ordertime_data['errors'] = $update_ordertime_data_errors;
                $update_ordertime_data['task_updatetime_product'] = time();
                table('site')
                    ->where('id', $site['id'])
                    ->update($update_ordertime_data);
                return 2;
            }
            $orders = $data['orders'];
            if (is_array($orders) && !empty($orders)) {
                date_default_timezone_set('Asia/Shanghai');
                $update_ordertime_data['updatetime_order'] = 0;
                foreach ($orders as  $order) {
                    $order_info = $this->model->where(['id' => $order['id']])->find();
                    $arr['id'] = $order['id'];
                    $arr['name'] = $order['name'];
                    $arr['number'] = $order['number'];
                    $arr['order_number'] = $order['order_number'];
                    $arr['ycreated_at'] = $order['created_at'];
                    $arr['yupdated_at'] = $order['updated_at'];

                    $arr['closed_at'] = $order['closed_at'];
                    //改变时间
                    if (!empty($arr['ycreated_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $arr['ycreated_at']);
                        $pos1 = strpos($ycreated_at2, '-');
                        if($pos1 !== false){
                            $arr['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                        }
                        $pos2 = strpos($ycreated_at2, '+');
                        if($pos2 !== false){
                            $arr['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                        }
                    }
                    $arr['created_at'] = strtotime($arr['created_at']);
                    //货币
                    $arr['currency'] = $order['currency'];
                    //支付状态
                    if (!empty($order['financial_status'])) {
                        $arr['financial_status'] = $order['financial_status'];
                    } else {
                        //自定义授权未完成
                        $arr['financial_status'] = DicOrder::$financial_status_unfulfilled;
                    }
                    $arr['ytotal_price'] = $order['total_price'];
                    $arr['total_price'] = $order['total_price'];
                    $arr['landing_site'] = $order['landing_site'] ?? "";

                    //customers_id
                    if (isset($order['customer']['id'])) {
                        $arr['customers_id'] = $order['customer']['id'];
                    } else {
                        $arr['customers_id'] = '';
                    }
                    //顾客总花费
                    if (isset($order['customer']['total_spent']) && $order['total_price'] == 0) {
                        $arr['total_price'] = $order['customer']['total_spent'];
                    }
                    if ($arr['financial_status'] == DicOrder::$financial_status_refunded) {
                        $arr['total_price'] = 0;
                    }
                    $arr['site_id'] = $site['id'];
                    //支付方式
                    if (!empty($order['payment_gateway_names'][0]) && isset($order['payment_gateway_names'][0])) {
                        $arr['gateway'] = $order['payment_gateway_names'][0];
                    }
                    if (!empty($order['tags'])) {
                        $arr['tags'] = $order['tags'];
                    } else {
                        $arr['tags'] = '暂无';
                    }
                    //如果接口返回空 则改成未发货
                    if (!empty($order['fulfillment_status'])) {
                        $arr['fulfillment_status'] = $order['fulfillment_status'];
                    } else {
                        $arr['fulfillment_status'] = DicOrder::$fulfillment_status_unshipped;
                    }

                    if ($order_info) {
                        //新增 大店不改tags
                        if($order_info['site_id'] == 121){
                            if($order_info['order_shecurve'] == 1){
                                unset($arr['tags']);
                            }
                        }
                        // if ($order_info['yupdated_at'] !== $arr['yupdated_at']) {
                            $this->model->where(['id' => $order['id']])->update($arr);
                        // }
                    } else {
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $this->model->insert($arr);
                    }
                    if (!empty($site['updatetime_order'])) {
                        //直接截取获得时间戳
                        $ycreated_atx = str_replace('T', ' ', $site['updatetime_order']);
                        $pos1 = strpos($ycreated_atx, '-');
                        if($pos1 !== false){
                            $ycreated_atx_new = substr($ycreated_atx, 0, strripos($ycreated_atx, '-'));
						}
                        $pos2 = strpos($ycreated_atx, '+');
                        if($pos2 !== false){
                            $ycreated_atx_new = substr($ycreated_atx, 0, strripos($ycreated_atx, '+'));
						}
                        
                        $ycreated_atx = strtotime($ycreated_atx_new);

                        if ($ycreated_atx > $arr['created_at']) {
                            if (!empty($zcreated_at)) {
                                if ($arr['created_at'] < $zcreated_at) {
                                    $zcreated_at = $arr['created_at'];
                                    $update_ordertime_data['updatetime_order'] = $arr['ycreated_at'];
                                }
                            } else {
                                $zcreated_at = $arr['created_at'];
                                $update_ordertime_data['updatetime_order'] = $arr['ycreated_at'];
                            }
                        } else {
                            $update_ordertime_data['updatetime_order'] = $site['updatetime_order'];
                        }
                    } else {
                        $update_ordertime_data['updatetime_order'] = $arr['ycreated_at'];
                    }
                }
                // table('site')
                //     ->where('id', $site['id'])
                //     ->update($update_ordertime_data);
            }
        }
        $update_ordertime_data['task_updatetime_product'] = time();
        table('site')
            ->where('id', $site['id'])
            ->update($update_ordertime_data);
        return 1;
    }


    /**
     *每分钟执行=>更新订单详情以及sku=>算业绩
     * 时间条件  updateordertime 升序
     */
    public function update_order_last_month($id = null)
    {
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_ids = input('site_ids');
            $where = array();
            if (!empty($site_ids)) {
                $where['site_id'] = $site_ids;
            } else {
                //从7店铺开始更新
                $where[] = ['site_id', '>=', 7];
            }

            $thismonth = date('m');
            $thisyear = date('Y');
            if ($thismonth == 1) {
                $lastmonth = 11;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 2) {
                $lastmonth = 12;
                $lastyear = $thisyear - 1;
            } else {
                $lastmonth = $thismonth - 2;
                $lastyear = $thisyear;
            }
            $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
            $lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay)) . ' 23:59:59';
            $b_time = strtotime($lastStartDay); //上个月的月初时间戳
            $e_time = strtotime($lastEndDay); //上个月的月末时间戳
            $where[] = ['created_at', '>=', $b_time];
            $where[] = ['created_at', '<=', $e_time];
            $orders = table('order')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('5')
                ->select()->toarray();
        }

        if (!empty($orders)) {
            $row = array();
            foreach ($orders as $order) {
                $site = table('site')
                    ->where('id', $order['site_id'])
                    ->find();
                if (empty($site)) {
                    $row_c['updateordertime'] = time();
                    table('order')
                        ->where('id', $order['id'])
                        ->update($row_c);
                    continue;
                }
                $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $order['id'] . ".json";
                $data = geturl($url, $site['apikey'], $site['apisecret']);
                $data = json_decode($data, true);
                $row = array();
                if (isset($data['order'])) {
                    //改变时间
                    if (!empty($data['order']['created_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $data['order']['created_at']);
                        $pos1 = strpos($ycreated_at2, '-');
                        if($pos1 !== false){
                            $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                        }
                        $pos2 = strpos($ycreated_at2, '+');
                        if($pos2 !== false){
                            $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                        }
                        
                    }
                    $row['ycreated_at'] = $data['order']['created_at'];
                    $row['created_at'] = strtotime($row['created_at']);
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {

                                $product_tags = array();
                                $url2 = $site['site_url'] . "/admin/api/2023-07/products/" . $line_item['product_id'] . ".json";
                                $data2 = geturl($url2, $site['apikey'], $site['apisecret']);
                                if ($data2) {
                                    $data2 = json_decode($data2, true);
                                    if (!empty($data2['product']['tags'])) {
                                        $product_tags = $data2['product']['tags'];
                                    }


                                    if (isset($data2['product']['images'][0]['src']) && !empty($data2['product']['images'][0]['src'])) {
                                        $product_images = $data2['product']['images'][0]['src'];
                                    }
                                }
                                //  TODO::原admin_type   adminid 需要确认读取标签的情况  
                                //只有在有对应店铺的情况才能读取标签
                                if ($site['adminid'] == 0) {
                                    $product_tags = array();
                                }
                                if (!empty($product_tags)) {
                                    if (!empty($product_tagsz)) {
                                        if ($product_tags !== $product_tagsz) {
                                            $product_tagsz = $product_tagsz . ',' . $product_tags;
                                        }
                                    } else {
                                        $product_tagsz = $product_tags;
                                    }
                                }

                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                //$arr['zmaterial'] = $arr['price'] * $arr['quantity'];
                                $arr['order_id'] = $order['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $order['created_at'];
                                $order_quantity = table('order_quantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->where('product_id', $arr['product_id'])
                                    ->find();
                                if (empty($order_quantity)) {
                                    table('order_quantity')->insert($arr);
                                } else {
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $arr['user_id'] = $product_tags;
                                        table('order_quantity')
                                            ->where('variant_id', $arr['variant_id'])
                                            ->where('order_id', $arr['order_id'])
                                            ->where('product_id', $arr['product_id'])
                                            ->update($arr);
                                    }
                                }
                                //商品记录
                                $order_product = table('order_product')->where('product_id', $arr['product_id'])->find();
                                if (empty($order_product)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['site_id'] = $order['site_id'];
                                    $product['product_name'] = $arr['title'];
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {
                                        $product['handle_url'] = $site['site_url'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product['product_images'] = $product_images;
                                    }
                                    table('order_product')->insert($product);
                                } else {
                                    //修改商品归属人
                                    $product2 = array();
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $product2['user_id'] = $data2['product']['tags'];
                                    }
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {

                                        $product2['handle_url'] = $site['site_url'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product2['product_images'] = $product_images;
                                    }
                                    if (!empty($product2)) {
                                        table('order_product')->where('product_id', $arr['product_id'])->update($product2);
                                    }
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $order_sku = table('order_sku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($order_sku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['site_id'] = $order['site_id'];
                                        table('order_sku')
                                            ->insert($sku_arr);
                                    } else {
                                        //修改SKU
                                        $sku2['sku'] = $arr['sku'];
                                        table('order_sku')->where('id', $order_sku['id'])->update($sku2);
                                    }
                                }
                                //往skuinventory库存表里加SKU数据
                                if (!empty($arr['product_id']) && !empty($arr['variant_id'])) {
                                    $skuinventory_info = table('skuinventory')
                                        ->where('product_id', $arr['product_id'])
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($skuinventory_info)) {
                                        $inventory['product_id'] = $arr['product_id'];
                                        $inventory['variants_id'] = $arr['variant_id'];
                                        if (!empty($arr['sku'])) {
                                            //组合SKU拆成多个 有+号代表组合SKU
                                            if (strpos($arr['sku'], '+') !== false) {
                                                $skus = explode('-', $arr['sku']);
                                                if (isset($skus[1]) && !empty($skus[1])) {
                                                    $skus2 = explode('+', $skus[1]);
                                                    if (!empty($skus2)) {
                                                        foreach ($skus2 as $k => $vskus2) {
                                                            $new_sku3[0] = $skus[0];
                                                            $new_sku3[1] = $vskus2;
                                                            if (isset($skus[2]) && !empty($skus[2])) {
                                                                $new_sku3[2] = $skus[2];
                                                            }
                                                            if (isset($skus[3]) && !empty($skus[3])) {
                                                                if ((int)($skus[3]) > 0) {
                                                                    //后缀是数字
                                                                    $inventory['sku_num'] = $skus[3];
                                                                }
                                                            }
                                                            $inventory['sku'] = implode('-', $new_sku3);
                                                            $inventory['brand'] = $skus[0];
                                                            table('skuinventory')->insert($inventory);
                                                        }
                                                    }
                                                }
                                            } else {
                                                $inventory['sku'] = $arr['sku'];
                                                $brand = explode('-', $arr['sku']);
                                                $inventory['brand'] = $brand[0];
                                                if (isset($brand[3]) && !empty($brand[3])) {
                                                    if ((int)($brand[3]) > 0) {
                                                        //后缀是数字
                                                        $inventory['sku_num'] = $brand[3];
                                                        //sku去掉卖货件数
                                                        $new2_sku[0] = $brand[0];
                                                        $new2_sku[1] = $brand[1];
                                                        $new2_sku[2] = $brand[2];
                                                        $inventory['sku'] = implode('-', $new2_sku);
                                                    }
                                                }
                                                table('skuinventory')->insert($inventory);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //新增商品物流单
                    if (isset($data['order']['fulfillments'])) {
                        $fulfillments = $data['order']['fulfillments'];
                        if (!empty($fulfillments)) {
                            table('order_fulfillments')
                                ->where('order_id', $order['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_ids'] = $line_item['id'];
                                $arr2['name'] = $line_item['name'];
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                table('order_fulfillments')->insert($arr2);
                                $row['tracking_number'] = $line_item['tracking_number'];
                                $row['tracking_company'] = $line_item['tracking_company'];
                                //如果有单号说明发货了
                                if (!empty($row['tracking_number'])) {
                                    $ycreated_at2 = str_replace('T', ' ', $line_item['created_at']);
                                    $pos1 = strpos($ycreated_at2, '-');
                                    if($pos1 !== false){
                                        $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                                    }
                                    $pos2 = strpos($ycreated_at2, '+');
                                    if($pos2 !== false){
                                        $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                                    }
                                    
                                    $row['tracking_time'] = strtotime($ycreated_at2_new);
                                }
                            }
                        }
                    }
                    //新增退款信息
                    if (isset($data['order']['refunds'])) {
                        $refunds = $data['order']['refunds'];
                        $arr_refunds = array();
                        if (!empty($refunds)) {
                            foreach ($refunds as $k => $v) {
                                if (!empty($v['transactions'])) {
                                    foreach ($v['transactions'] as $kt => $vt) {
                                        $arr_refund['order_id'] = $order['id'];
                                        $arr_refund['refund_id'] = $vt['id'];
                                        $arr_refund['created_at'] = $vt['created_at'];
                                        //改变时间
                                        if (!empty($vt['created_at'])) {
                                            //直接截取获得时间戳
                                            $ycreated_at3 = str_replace('T', ' ', $vt['created_at']);
                                            $pos1 = strpos($ycreated_at3, '-');
                                            if($pos1 !== false){
                                                $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '-'));
                                            }
                                            $pos2 = strpos($ycreated_at3, '+');
                                            if($pos2 !== false){
                                                $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '+'));
                                            }
                                        }
                                        $arr_refund['processed_at'] = strtotime($ycreated_at3_new);
                                        $arr_refund['amount'] = $vt['amount'];
                                        $arr_refund['currency'] = $vt['currency'];
                                        $arr_refund['gateway'] = $vt['gateway'];
                                        $arr_refund['message'] = $vt['message'];
                                        $arr_refund['refund_status'] = $vt['status'];
                                        $arr_refund['refunds_key'] = $kt;
                                        $arr_refund['createtime'] = time();
                                        $arr_refund['site_id'] = $order['site_id'];
                                        $arr_refund['order_name'] = $order['name'];
                                        $arr_refunds[] = $arr_refund;
                                    }
                                }
                            }
                        }
                        if (!empty($arr_refunds)) {
                            table('order_refunds')
                                ->where('order_id', $order['id'])
                                ->delete();
                            table('order_refunds')->insertAll($arr_refunds);
                        }
                    }
                    //更新订单状态
                    if (!empty($data['order']['financial_status'])) {
                        //如果是退款的 部分退款的订单则不实时更新状态了
                        if ($data['order']['financial_status'] == DicOrder::$financial_status_refunded || $data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                            //也更新状态
                            $row['financial_status'] = $data['order']['financial_status'];
                        } else {
                            $row['financial_status'] = $data['order']['financial_status'];
                        }
                    } else {
                        $row['financial_status'] = DicOrder::$fulfillment_status_unfulfilled;;
                    }

                    //如果接口返回空 则改成未发货
                    if (!empty($data['order']['fulfillment_status'])) {
                        $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    } else {
                        $row['fulfillment_status'] = DicOrder::$fulfillment_status_unshipped;
                    }

                    //更新订单最新价格
                    $row['total_price'] = $data['order']['total_price'];
                    //部分退款计入金额
                    if ($data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                        $row['total_price'] = $data['order']['subtotal_price'];
                    }
                    //计算小费
                    if (!empty($data['order']['total_tip_received'])) {
                        $row['total_tip_received'] = $data['order']['total_tip_received'];
                    }

                    if (isset($data['order']['customer']['total_spent']) && $data['order']['customer']['total_spent'] > 0 && $data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                        $row['total_price'] = $data['order']['customer']['total_spent'];
                    }
                    if ($data['order']['financial_status'] == DicOrder::$financial_status_refunded) {
                        $row['total_price'] = 0;
                    }
                    //新增明细
                    if (isset($data['order']['current_subtotal_price'])) {
                        $row['current_subtotal_price'] = $data['order']['current_subtotal_price'];
                    } else {
                        $row['current_subtotal_price'] = 0;
                    }
                    // 可能是total_line_items_price
                    if (isset($data['order']['total_shipping_price_set']['shop_money']['amount'])) {
                        $row['total_shipping_price_set'] = $data['order']['total_shipping_price_set']['shop_money']['amount'];
                    } else {
                        $row['total_shipping_price_set'] = 0;
                    }

                    //联系人
                    if (isset($data['order']['customer']['email'])) {
                        $row['email'] = $data['order']['customer']['email'];
                    } else {
                        $row['email'] = '';
                    }

                    if (isset($data['order']['customer']['id'])) {
                        $row['customers_id'] = $data['order']['customer']['id'];
                    } else {
                        $row['customers_id'] = '';
                    }

                    if (isset($data['order']['shipping_address']['name'])) {
                        $row['shipping_name'] = $data['order']['shipping_address']['name'];
                    } else {
                        $row['shipping_name'] = '';
                    }
                    if (isset($data['order']['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "", $data['order']['shipping_address']['phone']);
                    } else {
                        $row['phone'] = '';
                    }
                    if (isset($data['order']['shipping_address']['province'])) {
                        $row['province'] = $data['order']['shipping_address']['province'];
                    } else {
                        $row['province'] = '';
                    }
                    if (isset($data['order']['shipping_address']['city'])) {
                        $row['city'] = $data['order']['shipping_address']['city'];
                    } else {
                        $row['city'] = '';
                    }
                    if (isset($data['order']['shipping_address']['zip'])) {
                        $row['zip'] = $data['order']['shipping_address']['zip'];
                    } else {
                        $row['zip'] = '';
                    }
                    if (isset($data['order']['shipping_address']['address1'])) {
                        $row['address1'] = $data['order']['shipping_address']['address1'];
                    } else {
                        $row['address1'] = '';
                    }
                    if (isset($data['order']['shipping_address']['country_code'])) {
                        $row['country_code'] = $data['order']['shipping_address']['country_code'];
                    } else {
                        $row['country_code'] = '';
                    }
                    if (isset($data['order']['order_status_url'])) {
                        $row['order_status_url'] = $data['order']['order_status_url'];
                    } else {
                        $row['order_status_url'] = '';
                    }
                    //note
                    $row['note'] = $data['order']['note'];

                    $row['closed_at'] = $data['order']['closed_at'];

                    if (!empty($data['order']['tags'])) {
                        $row['tags'] = $data['order']['tags'];
                    } else {
                        $row['tags'] = '暂无';
                    }

                    $row['referring_site'] = $data['order']['referring_site'];
                    $row['landing_site'] = $data['order']['landing_site'];
                    $row['current_total_discounts'] = $data['order']['current_total_discounts'];
                    $row['current_total_tax'] = $data['order']['current_total_tax'];
                    //referring_site是空且landing_site带/的不要，instagram facebook不要
                    //该订单当前归属人
                    // $wheregroup['createtime'] = array('elt', $row['created_at']);
                    // $wheregroup[] = ['createtime', '<=', $row['created_at']];
                    // // $wheregroup['updatetime'] = array('egt', $row['created_at']);
                    // $wheregroup[] = ['updatetime', '>=', $row['created_at']];
                    // table('site_group')
                    //     ->where('site_id', $site['id'])
                    //     ->where($wheregroup)
                    //     ->find();
                    // if (!empty($accounturlgroup)) {
                    //     $admin = table('admin')->where('id', $accounturlgroup['admin_id'])->find();
                    // }
                    //优先接口的标签
                    if (!empty($product_tagsz)) {
                        $row['user_id'] = $product_tagsz;
                        //再加店铺归属人
                        // if (!empty($admin) && $admin['id'] !== 1) {
                        //     $row['user_id'] = $row['user_id'].','.$admin['username'];
                        // }
                    } else {
                        //如果没有标签则用店铺归属人
                        // if (!empty($admin)) {
                        //     $row['user_id'] = $admin['username'];
                        // }else{
                        $row['user_id'] = 'Admin';
                        // }
                    }
                }
                $row['updateordertime'] = time();
                //同步物流消息
                //if (empty($row['tracking_number'])) {
                $order_fulfillments = table('order_fulfillments')->where('order_id', $order['id'])->find();
                if (!empty($order_fulfillments)) {
                    $row['tracking_number'] = $order_fulfillments['tracking_number'];
                    $row['tracking_company'] = $order_fulfillments['tracking_company'];
                    $order_fulfillments['order_id'] = $order['id'];
                } else {
                    $row['tracking_number'] = '';
                    $row['tracking_company'] = '';
                }
                //                }
                table('order')
                    ->where('id', $order['id'])
                    ->update($row);
                //更新交易
                // $this->update_order_transactions($order['id']);
            }
            return   success('操作成功');
        } else {
            return   error('未找到相关订单');
        }
    }

    /**
     *每分钟执行----更新前四个月订单=>统计销量
     */
    public function update_order_4month($id = null)
    {
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_ids = input('site_ids');
            $where = array();
            if (!empty($site_ids)) {
                $where['site_id'] = $site_ids;
            } else {
                //从7店铺开始更新
                // $where['site_id']  = array('egt', 7);
                $where[]  = ['site_id', '>=', 7];
            }
            $thismonth = date('m');
            $thisyear = date('Y');
            if ($thismonth == 1) {
                $lastmonth = 10;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 2) {
                $lastmonth = 11;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 3) {
                $lastmonth = 12;
                $lastyear = $thisyear - 1;
            } else {
                $lastmonth = $thismonth - 3;
                $lastyear = $thisyear;
            }
            $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
            $b_time = strtotime($lastStartDay);
            $e_time = time();
            // $where['created_at'] = array(array('egt', $b_time), array('elt', $e_time));
            $where[] = ['created_at', '>=', $b_time];
            $where[] = ['created_at', '<=', $e_time];
            $orders = table('order')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('5')
                ->select()->toarray();
        }
        if (!empty($orders)) {
            $row = array();
            foreach ($orders as $order) {
                $site = table('site')
                    ->where('id', $order['site_id'])
                    ->find();
                if (empty($site)) {
                    $row_c['updateordertime'] = time();
                    table('order')
                        ->where('id', $order['id'])
                        ->update($row_c);
                    continue;
                }
                $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $order['id'] . ".json";
                $data = geturl($url, $site['apikey'], $site['apisecret']);
                $data = json_decode($data, true);
                $row = array();
                if (isset($data['order'])) {
                    if(!empty($data['order']['discount_codes'])) {
                        if(isset($data['order']['discount_codes'][0]['code']) && !empty($data['order']['discount_codes'][0]['code'])) {
                            $row['discount_code'] = $data['order']['discount_codes'][0]['code'];
                        }
                    }
                    //改变时间
                    if (!empty($data['order']['created_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $data['order']['created_at']);
                        $pos1 = strpos($ycreated_at2, '-');
                        if($pos1 !== false){
                            $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                        }
                        $pos2 = strpos($ycreated_at2, '+');
                        if($pos2 !== false){
                            $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                        }
                        
                    }
                    $row['ycreated_at'] = $data['order']['created_at'];
                    $row['created_at'] = strtotime($row['created_at']);
                    $product_tagsz = '';
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {

                                $product_tags = array();
                                $url2 = $site['site_url'] . "/admin/api/2023-07/products/" . $line_item['product_id'] . ".json";
                                $data2 = geturl($url2, $site['apikey'], $site['apisecret']);
                                if ($data2) {
                                    $data2 = json_decode($data2, true);
                                    if (!empty($data2['product']['tags'])) {
                                        $product_tags = $data2['product']['tags'];
                                    }


                                    if (isset($data2['product']['images'][0]['src']) && !empty($data2['product']['images'][0]['src'])) {
                                        $product_images = $data2['product']['images'][0]['src'];
                                    }
                                }
                                // TODO:: 原admin_type改为adminid
                                //只有在有对应店铺的情况才能读取标签
                                if ($site['adminid'] == 0) {
                                    $product_tags = array();
                                }
                                if (!empty($product_tags)) {
                                    if (!empty($product_tagsz)) {
                                        if ($product_tags !== $product_tagsz) {
                                            $product_tagsz = $product_tagsz . ',' . $product_tags;
                                        }
                                    } else {
                                        $product_tagsz = $product_tags;
                                    }
                                }

                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                //$arr['zmaterial'] = $arr['price'] * $arr['quantity'];
                                $arr['order_id'] = $order['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $order['created_at'];
                                $order_quantity = table('order_quantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->where('product_id', $arr['product_id'])
                                    ->find();
                                if (empty($order_quantity)) {
                                    table('order_quantity')->insert($arr);
                                } else {
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $arr['user_id'] = $product_tags;
                                        table('order_quantity')
                                            ->where('variant_id', $arr['variant_id'])
                                            ->where('order_id', $arr['order_id'])
                                            ->where('product_id', $arr['product_id'])
                                            ->update($arr);
                                    }
                                }
                                //商品记录
                                $order_product = table('order_product')->where('product_id', $arr['product_id'])->find();
                                if (empty($order_product)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['site_id'] = $order['site_id'];
                                    $product['product_name'] = $arr['title'];
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {
                                        $product['handle_url'] = $site['site_url'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product['product_images'] = $product_images;
                                    }
                                    table('order_product')->insert($product);
                                } else {
                                    //修改商品归属人
                                    $product2 = array();
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $product2['user_id'] = $data2['product']['tags'];
                                    }
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {

                                        $product2['handle_url'] = $site['site_url'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product2['product_images'] = $product_images;
                                    }
                                    if (!empty($product2)) {
                                        table('order_product')->where('product_id', $arr['product_id'])->update($product2);
                                    }
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $order_sku = table('order_sku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($order_sku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['site_id'] = $order['site_id'];
                                        table('order_sku')
                                            ->insert($sku_arr);
                                    } else {
                                        //修改SKU
                                        $sku2['sku'] = $arr['sku'];
                                        table('order_sku')->where('id', $order_sku['id'])->update($sku2);
                                    }
                                }
                                //往skuinventory库存表里加SKU数据
                                if (!empty($arr['product_id']) && !empty($arr['variant_id'])) {
                                    $skuinventory_info = table('skuinventory')
                                        ->where('product_id', $arr['product_id'])
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($skuinventory_info)) {
                                        $inventory['product_id'] = $arr['product_id'];
                                        $inventory['variants_id'] = $arr['variant_id'];
                                        if (!empty($arr['sku'])) {
                                            //组合SKU拆成多个 有+号代表组合SKU
                                            if (strpos($arr['sku'], '+') !== false) {
                                                $skus = explode('-', $arr['sku']);
                                                if (isset($skus[1]) && !empty($skus[1])) {
                                                    $skus2 = explode('+', $skus[1]);
                                                    if (!empty($skus2)) {
                                                        foreach ($skus2 as $k => $vskus2) {
                                                            $new_sku3[0] = $skus[0];
                                                            $new_sku3[1] = $vskus2;
                                                            if (isset($skus[2]) && !empty($skus[2])) {
                                                                $new_sku3[2] = $skus[2];
                                                            }
                                                            if (isset($skus[3]) && !empty($skus[3])) {
                                                                if ((int)($skus[3]) > 0) {
                                                                    //后缀是数字
                                                                    $inventory['sku_num'] = $skus[3];
                                                                }
                                                            }
                                                            $inventory['sku'] = implode('-', $new_sku3);
                                                            $inventory['brand'] = $skus[0];
                                                            table('skuinventory')->insert($inventory);
                                                        }
                                                    }
                                                }
                                            } else {
                                                $inventory['sku'] = $arr['sku'];
                                                $brand = explode('-', $arr['sku']);
                                                $inventory['brand'] = $brand[0];
                                                if (isset($brand[3]) && !empty($brand[3])) {
                                                    if ((int)($brand[3]) > 0) {
                                                        //后缀是数字
                                                        $inventory['sku_num'] = $brand[3];
                                                        //sku去掉卖货件数
                                                        $new2_sku[0] = $brand[0];
                                                        $new2_sku[1] = $brand[1];
                                                        $new2_sku[2] = $brand[2];
                                                        $inventory['sku'] = implode('-', $new2_sku);
                                                    }
                                                }
                                                table('skuinventory')->insert($inventory);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //新增商品物流单
                    if (isset($data['order']['fulfillments'])) {
                        $fulfillments = $data['order']['fulfillments'];
                        if (!empty($fulfillments)) {
                            table('order_fulfillments')
                                ->where('order_id', $order['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_ids'] = $line_item['id'];
                                $arr2['name'] = $line_item['name'];
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                table('order_fulfillments')->insert($arr2);
                                $row['tracking_number'] = $line_item['tracking_number'];
                                $row['tracking_company'] = $line_item['tracking_company'];
                                //如果有单号说明发货了
                                if (!empty($row['tracking_number'])) {
                                    $ycreated_at2 = str_replace('T', ' ', $line_item['created_at']);
                                    $pos1 = strpos($ycreated_at2, '-');
                                    if($pos1 !== false){
                                        $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                                    }
                                    $pos2 = strpos($ycreated_at2, '+');
                                    if($pos2 !== false){
                                        $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                                    }
                                    $row['tracking_time'] = strtotime($ycreated_at2_new);
                                }
                            }
                        }
                    }
                    //新增退款信息
                    if (isset($data['order']['refunds'])) {
                        $refunds = $data['order']['refunds'];
                        $arr_refunds = array();
                        if (!empty($refunds)) {
                            foreach ($refunds as $k => $v) {
                                if (!empty($v['transactions'])) {
                                    foreach ($v['transactions'] as $kt => $vt) {
                                        $arr_refund['order_id'] = $order['id'];
                                        $arr_refund['refund_id'] = $vt['id'];
                                        $arr_refund['created_at'] = $vt['created_at'];
                                        //改变时间
                                        if (!empty($vt['created_at'])) {
                                            //直接截取获得时间戳
                                            $ycreated_at3 = str_replace('T', ' ', $vt['created_at']);
                                            $pos1 = strpos($ycreated_at3, '-');
                                            if($pos1 !== false){
                                                $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '-'));
                                            }
                                            $pos2 = strpos($ycreated_at3, '+');
                                            if($pos2 !== false){
                                                $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '+'));
                                            }
                                            
                                        }
                                        $arr_refund['processed_at'] = strtotime($ycreated_at3_new);
                                        $arr_refund['amount'] = $vt['amount'];
                                        $arr_refund['currency'] = $vt['currency'];
                                        $arr_refund['gateway'] = $vt['gateway'];
                                        $arr_refund['message'] = $vt['message'];
                                        $arr_refund['refund_status'] = $vt['status'];
                                        $arr_refund['refunds_key'] = $kt;
                                        $arr_refund['createtime'] = time();
                                        $arr_refund['site_id'] = $order['site_id'];
                                        $arr_refund['order_name'] = $order['name'];
                                        $arr_refunds[] = $arr_refund;
                                    }
                                }
                            }
                        }
                        if (!empty($arr_refunds)) {
                            table('order_refunds')
                                ->where('order_id', $order['id'])
                                ->delete();
                            table('order_refunds')->insertAll($arr_refunds);
                        }
                    }
                    //更新订单状态
                    if (!empty($data['order']['financial_status'])) {
                        //如果是退款的 部分退款的订单则不实时更新状态了
                        if ($data['order']['financial_status'] == DicOrder::$financial_status_refunded || $data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                            //也更新状态
                            $row['financial_status'] = $data['order']['financial_status'];
                        } else {
                            $row['financial_status'] = $data['order']['financial_status'];
                        }
                    } else {
                        $row['financial_status'] = DicOrder::$fulfillment_status_unfulfilled;;
                    }
                    //如果接口返回空 则改成未发货
                    if (!empty($data['order']['fulfillment_status'])) {
                        $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    } else {
                        $row['fulfillment_status'] = DicOrder::$fulfillment_status_unshipped;
                    }
                    //更新订单最新价格
                    $row['total_price'] = $data['order']['total_price'];
                    //部分退款计入金额
                    if ($data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                        $row['total_price'] = $data['order']['subtotal_price'];
                    }
                    
                    //计算小费
                    if (!empty($data['order']['total_tip_received'])) {
                        $row['total_tip_received'] = $data['order']['total_tip_received'];
                    }

                    if (isset($data['order']['customer']['total_spent']) && $data['order']['customer']['total_spent'] > 0 && $data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                        $row['total_price'] = $data['order']['customer']['total_spent'];
                    }
                    if ($data['order']['financial_status'] == DicOrder::$financial_status_refunded) {
                        $row['total_price'] = 0;
                    }
                    //新增明细
                    if (isset($data['order']['current_subtotal_price'])) {
                        $row['current_subtotal_price'] = $data['order']['current_subtotal_price'];
                    } else {
                        $row['current_subtotal_price'] = 0;
                    }
                    // 可能是total_line_items_price
                    if (isset($data['order']['total_shipping_price_set']['shop_money']['amount'])) {
                        $row['total_shipping_price_set'] = $data['order']['total_shipping_price_set']['shop_money']['amount'];
                    } else {
                        $row['total_shipping_price_set'] = 0;
                    }

                    //联系人
                    if (isset($data['order']['customer']['email'])) {
                        $row['email'] = $data['order']['customer']['email'];
                    } else {
                        $row['email'] = '';
                    }

                    if (isset($data['order']['customer']['id'])) {
                        $row['customers_id'] = $data['order']['customer']['id'];
                    } else {
                        $row['customers_id'] = '';
                    }

                    if (isset($data['order']['shipping_address']['name'])) {
                        $row['shipping_name'] = $data['order']['shipping_address']['name'];
                    } else {
                        $row['shipping_name'] = '';
                    }
                    if (isset($data['order']['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "", $data['order']['shipping_address']['phone']);
                    } else {
                        $row['phone'] = '';
                    }
                    if (isset($data['order']['shipping_address']['province'])) {
                        $row['province'] = $data['order']['shipping_address']['province'];
                    } else {
                        $row['province'] = '';
                    }
                    if (isset($data['order']['shipping_address']['city'])) {
                        $row['city'] = $data['order']['shipping_address']['city'];
                    } else {
                        $row['city'] = '';
                    }
                    if (isset($data['order']['shipping_address']['zip'])) {
                        $row['zip'] = $data['order']['shipping_address']['zip'];
                    } else {
                        $row['zip'] = '';
                    }
                    if (isset($data['order']['shipping_address']['address1'])) {
                        $row['address1'] = $data['order']['shipping_address']['address1'];
                    } else {
                        $row['address1'] = '';
                    }
                    if (isset($data['order']['shipping_address']['country_code'])) {
                        $row['country_code'] = $data['order']['shipping_address']['country_code'];
                    } else {
                        $row['country_code'] = '';
                    }
                    if (isset($data['order']['order_status_url'])) {
                        $row['order_status_url'] = $data['order']['order_status_url'];
                    } else {
                        $row['order_status_url'] = '';
                    }
                    //note
                    $row['note'] = $data['order']['note'];
                    $row['closed_at'] = $data['order']['closed_at'];

                    if (!empty($data['order']['tags'])) {
                        $row['tags'] = $data['order']['tags'];
                    } else {
                        $row['tags'] = '暂无';
                    }

                    $row['referring_site'] = $data['order']['referring_site'];
                    $row['landing_site'] = $data['order']['landing_site'];
                    $row['current_total_discounts'] = $data['order']['current_total_discounts'];
                    $row['current_total_tax'] = $data['order']['current_total_tax'];
                    //referring_site是空且landing_site带/的不要，instagram facebook不要
                    //该订单当前归属人
                    // $wheregroup['createtime'] = array('elt', $row['created_at']);
                    // $wheregroup[] = ['createtime', '<=', $row['created_at']];
                    // // $wheregroup['updatetime'] = array('egt', $row['created_at']);
                    // $wheregroup[] = ['updatetime', '>=', $row['created_at']];

                    // table('site_group')
                    //     ->where('site_id', $site['id'])
                    //     ->where($wheregroup)
                    //     ->find();
                    // if (!empty($accounturlgroup)) {
                    //     $admin = table('admin')->where('id', $accounturlgroup['admin_id'])->find();
                    // }
                    //优先接口的标签
                    if (!empty($product_tagsz)) {
                        $row['user_id'] = $product_tagsz;
                        //再加店铺归属人
                        // if (!empty($admin) && $admin['id'] !== 1) {
                        //     $row['user_id'] = $row['user_id'].','.$admin['username'];
                        // }
                    } else {
                        //如果没有标签则用店铺归属人
                        // if (!empty($admin)) {
                        //     $row['user_id'] = $admin['username'];
                        // }else{
                        $row['user_id'] = 'Admin';
                        // }
                    }
                }
                $row['updateordertime'] = time();
                //同步物流消息
                //if (empty($row['tracking_number'])) {
                $order_fulfillments = table('order_fulfillments')->where('order_id', $order['id'])->find();
                if (!empty($order_fulfillments)) {
                    $row['tracking_number'] = $order_fulfillments['tracking_number'];
                    $row['tracking_company'] = $order_fulfillments['tracking_company'];
                    $order_fulfillments['order_id'] = $order['id'];
                } else {
                    $row['tracking_number'] = '';
                    $row['tracking_company'] = '';
                }
                //                }
                table('order')
                    ->where('id', $order['id'])
                    ->update($row);
                //更新交易
                // $this->update_order_transactions($order['id']);
            }
            return success('操作成功');
        } else {
            return error('未找到相关订单');
        }
    }

    /**
     *每分钟执行----更新订单的sku
     */
    public function update_order_4month_sku($id = null)
    {
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_ids = input('site_ids');
            $where = array();
            if (!empty($site_ids)) {
                $where['site_id'] = $site_ids;
            } else {
                $where[]  = ['site_id', '>=', 7];
            }
            $b_time = strtotime('-77 days');
            $e_time = time();
            $where[] = ['created_at', '>=', $b_time];
            $where[] = ['created_at', '<=', $e_time];
            $orders = table('order')
                ->order('updateordertime_sku asc')
                ->where($where)
                ->limit('10')
                ->select()->toarray();
        }
        if (!empty($orders)) {
            $row = array();
            foreach ($orders as $order) {
                $site = table('site')
                    ->where('id', $order['site_id'])
                    ->find();
                if (empty($site)) {
                    $row_c['updateordertime_sku'] = time();
                    table('order')
                        ->where('id', $order['id'])
                        ->update($row_c);
                    continue;
                }
                $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $order['id'] . ".json";
                $data = geturl($url, $site['apikey'], $site['apisecret']);
                $data = json_decode($data, true);
                $row = array();
                if (isset($data['order'])) {
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {
                                $url2 = $site['site_url'] . "/admin/api/2023-07/products/" . $line_item['product_id'] . ".json";
                                $data2 = geturl($url2, $site['apikey'], $site['apisecret']);
                                if ($data2) {
                                    $data2 = json_decode($data2, true);
                                    if (isset($data2['product']['images'][0]['src']) && !empty($data2['product']['images'][0]['src'])) {
                                        $product_images = $data2['product']['images'][0]['src'];
                                    }
                                }
                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                $arr['order_id'] = $order['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $order['created_at'];
                                $order_quantity = table('order_quantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->where('product_id', $arr['product_id'])
                                    ->find();
                                if (empty($order_quantity)) {
                                    table('order_quantity')->insert($arr);
                                } else {
                                    table('order_quantity')
                                        ->where('variant_id', $arr['variant_id'])
                                        ->where('order_id', $arr['order_id'])
                                        ->where('product_id', $arr['product_id'])
                                        ->update($arr);
                                }
                                //商品记录
                                $order_product = table('order_product')->where('product_id', $arr['product_id'])->find();
                                if (empty($order_product)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['site_id'] = $order['site_id'];
                                    $product['product_name'] = $arr['title'];
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {
                                        $product['handle_url'] = $site['site_url'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product['product_images'] = $product_images;
                                    }
                                    table('order_product')->insert($product);
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $order_sku = table('order_sku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($order_sku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['site_id'] = $order['site_id'];
                                        table('order_sku')
                                            ->insert($sku_arr);
                                    } else {
                                        //修改SKU
                                        $sku2['sku'] = $arr['sku'];
                                        table('order_sku')->where('id', $order_sku['id'])->update($sku2);
                                    }
                                }
                                //往skuinventory库存表里加SKU数据
                                if (!empty($arr['product_id']) && !empty($arr['variant_id'])) {
                                    $skuinventory_info = table('skuinventory')
                                        ->where('product_id', $arr['product_id'])
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($skuinventory_info)) {
                                        $inventory['product_id'] = $arr['product_id'];
                                        $inventory['variants_id'] = $arr['variant_id'];
                                        if (!empty($arr['sku'])) {
                                            //组合SKU拆成多个 有+号代表组合SKU
                                            if (strpos($arr['sku'], '+') !== false) {
                                                $skus = explode('-', $arr['sku']);
                                                if (isset($skus[1]) && !empty($skus[1])) {
                                                    $skus2 = explode('+', $skus[1]);
                                                    if (!empty($skus2)) {
                                                        foreach ($skus2 as $k => $vskus2) {
                                                            $new_sku3[0] = $skus[0];
                                                            $new_sku3[1] = $vskus2;
                                                            if (isset($skus[2]) && !empty($skus[2])) {
                                                                $new_sku3[2] = $skus[2];
                                                            }
                                                            if (isset($skus[3]) && !empty($skus[3])) {
                                                                if ((int)($skus[3]) > 0) {
                                                                    //后缀是数字
                                                                    $inventory['sku_num'] = $skus[3];
                                                                }
                                                            }
                                                            $inventory['sku'] = implode('-', $new_sku3);
                                                            $inventory['brand'] = $skus[0];
                                                            table('skuinventory')->insert($inventory);
                                                        }
                                                    }
                                                }
                                            } else {
                                                $inventory['sku'] = $arr['sku'];
                                                $brand = explode('-', $arr['sku']);
                                                $inventory['brand'] = $brand[0];
                                                if (isset($brand[3]) && !empty($brand[3])) {
                                                    if ((int)($brand[3]) > 0) {
                                                        //后缀是数字
                                                        $inventory['sku_num'] = $brand[3];
                                                        //sku去掉卖货件数
                                                        $new2_sku[0] = $brand[0];
                                                        $new2_sku[1] = $brand[1];
                                                        $new2_sku[2] = $brand[2];
                                                        $inventory['sku'] = implode('-', $new2_sku);
                                                    }
                                                }
                                                table('skuinventory')->insert($inventory);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                $row['updateordertime_sku'] = time();
                table('order')
                    ->where('id', $order['id'])
                    ->update($row);
            }
            return success('操作成功');
        } else {
            return error('未找到相关订单');
        }
    }

    /**
     *每分钟执行----更新三天订单=>统计sku
     */
    public function update_order_3day($id = null)
    {
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_id = input('site_id');
            if (!empty($site_id)) {
                $where[] = ['site_id', '=', $site_id];
            }
            $b_time = strtotime('-10 days');
            $e_time = time();
            // $where['created_at'] = array(array('egt', $b_time), array('elt', $e_time));
            $where[] = ['created_at', '>=', $b_time];
            $where[] = ['created_at', '<=', $e_time];
            // $where['site_url'] = array('in', '59,79,81');
            $orders = table('order')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('5')
                ->select()->toarray();
        }
        if (!empty($orders)) {
            $row = array();
            foreach ($orders as $order) {
                $site = table('site')
                    ->where('id', $order['site_id'])
                    ->find();
                if (empty($site)) {
                    $row_c['updateordertime'] = time();
                    table('order')
                        ->where('id', $order['id'])
                        ->update($row_c);
                    continue;
                }
                $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $order['id'] . ".json";
                $data = geturl($url, $site['apikey'], $site['apisecret']);
                $data = json_decode($data, true);
                $row = array();
                if (isset($data['order'])) {
                    //改变时间
                    if (!empty($data['order']['created_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $data['order']['created_at']);
                        $pos1 = strpos($ycreated_at2, '-');
                        if($pos1 !== false){
                            $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                        }
                        $pos2 = strpos($ycreated_at2, '+');
                        if($pos2 !== false){
                            $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                        }
                        
                    }
                    $row['ycreated_at'] = $data['order']['created_at'];
                    $row['created_at'] = strtotime($row['created_at']);
                    $product_tagsz = '';
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {

                                $product_tags = array();
                                $url2 = $site['site_url'] . "/admin/api/2023-07/products/" . $line_item['product_id'] . ".json";
                                $data2 = geturl($url2, $site['apikey'], $site['apisecret']);
                                if ($data2) {
                                    $data2 = json_decode($data2, true);
                                    if (!empty($data2['product']['tags'])) {
                                        $product_tags = $data2['product']['tags'];
                                    }


                                    if (isset($data2['product']['images'][0]['src']) && !empty($data2['product']['images'][0]['src'])) {
                                        $product_images = $data2['product']['images'][0]['src'];
                                    }
                                }
                                // TODO:: 原admin_type改为adminid
                                //只有在有对应店铺的情况才能读取标签
                                if ($site['adminid'] == 0) {
                                    $product_tags = array();
                                }
                                if (!empty($product_tags)) {
                                    if (!empty($product_tagsz)) {
                                        if ($product_tags !== $product_tagsz) {
                                            $product_tagsz = $product_tagsz . ',' . $product_tags;
                                        }
                                    } else {
                                        $product_tagsz = $product_tags;
                                    }
                                }

                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                //$arr['zmaterial'] = $arr['price'] * $arr['quantity'];
                                $arr['order_id'] = $order['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $order['created_at'];
                                $order_quantity = table('order_quantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->where('product_id', $arr['product_id'])
                                    ->find();
                                if (empty($order_quantity)) {
                                    table('order_quantity')->insert($arr);
                                } else {
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $arr['user_id'] = $product_tags;
                                        table('order_quantity')
                                            ->where('variant_id', $arr['variant_id'])
                                            ->where('order_id', $arr['order_id'])
                                            ->where('product_id', $arr['product_id'])
                                            ->update($arr);
                                    }
                                }
                                //商品记录
                                $order_product = table('order_product')->where('product_id', $arr['product_id'])->find();
                                if (empty($order_product)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['site_id'] = $order['site_id'];
                                    $product['product_name'] = $arr['title'];
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {
                                        $product['handle_url'] = $site['site_url'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product['product_images'] = $product_images;
                                    }
                                    table('order_product')->insert($product);
                                } else {
                                    //修改商品归属人
                                    $product2 = array();
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $product2['user_id'] = $data2['product']['tags'];
                                    }
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {

                                        $product2['handle_url'] = $site['site_url'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product2['product_images'] = $product_images;
                                    }
                                    if (!empty($product2)) {
                                        table('order_product')->where('product_id', $arr['product_id'])->update($product2);
                                    }
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $order_sku = table('order_sku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($order_sku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['site_id'] = $order['site_id'];
                                        table('order_sku')
                                            ->insert($sku_arr);
                                    } else {
                                        //修改SKU
                                        $sku2['sku'] = $arr['sku'];
                                        table('order_sku')->where('id', $order_sku['id'])->update($sku2);
                                    }
                                }
                                //往skuinventory库存表里加SKU数据
                                if (!empty($arr['product_id']) && !empty($arr['variant_id'])) {
                                    $skuinventory_info = table('skuinventory')
                                        ->where('product_id', $arr['product_id'])
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($skuinventory_info)) {
                                        $inventory['product_id'] = $arr['product_id'];
                                        $inventory['variants_id'] = $arr['variant_id'];
                                        if (!empty($arr['sku'])) {
                                            //组合SKU拆成多个 有+号代表组合SKU
                                            if (strpos($arr['sku'], '+') !== false) {
                                                $skus = explode('-', $arr['sku']);
                                                if (isset($skus[1]) && !empty($skus[1])) {
                                                    $skus2 = explode('+', $skus[1]);
                                                    if (!empty($skus2)) {
                                                        foreach ($skus2 as $k => $vskus2) {
                                                            $new_sku3[0] = $skus[0];
                                                            $new_sku3[1] = $vskus2;
                                                            if (isset($skus[2]) && !empty($skus[2])) {
                                                                $new_sku3[2] = $skus[2];
                                                            }
                                                            if (isset($skus[3]) && !empty($skus[3])) {
                                                                if ((int)($skus[3]) > 0) {
                                                                    //后缀是数字
                                                                    $inventory['sku_num'] = $skus[3];
                                                                }
                                                            }
                                                            $inventory['sku'] = implode('-', $new_sku3);
                                                            $inventory['brand'] = $skus[0];
                                                            table('skuinventory')->insert($inventory);
                                                        }
                                                    }
                                                }
                                            } else {
                                                $inventory['sku'] = $arr['sku'];
                                                $brand = explode('-', $arr['sku']);
                                                $inventory['brand'] = $brand[0];
                                                if (isset($brand[3]) && !empty($brand[3])) {
                                                    if ((int)($brand[3]) > 0) {
                                                        //后缀是数字
                                                        $inventory['sku_num'] = $brand[3];
                                                        //sku去掉卖货件数
                                                        $new2_sku[0] = $brand[0];
                                                        $new2_sku[1] = $brand[1];
                                                        $new2_sku[2] = $brand[2];
                                                        $inventory['sku'] = implode('-', $new2_sku);
                                                    }
                                                }
                                                table('skuinventory')->insert($inventory);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //新增商品物流单
                    if (isset($data['order']['fulfillments'])) {
                        $fulfillments = $data['order']['fulfillments'];
                        if (!empty($fulfillments)) {
                            table('order_fulfillments')
                                ->where('order_id', $order['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_ids'] = $line_item['id'];
                                $arr2['name'] = $line_item['name'];
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                table('order_fulfillments')->insert($arr2);
                                $row['tracking_number'] = $line_item['tracking_number'];
                                $row['tracking_company'] = $line_item['tracking_company'];
                                //如果有单号说明发货了
                                if (!empty($row['tracking_number'])) {
                                    $ycreated_at2 = str_replace('T', ' ', $line_item['created_at']);
                                    $pos1 = strpos($ycreated_at2, '-');
                                    if($pos1 !== false){
                                        $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                                    }
                                    $pos2 = strpos($ycreated_at2, '+');
                                    if($pos2 !== false){
                                        $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                                    }
                                    
                                    $row['tracking_time'] = strtotime($ycreated_at2_new);
                                }
                            }
                        }
                    }
                    //新增退款信息
                    if (isset($data['order']['refunds'])) {
                        $refunds = $data['order']['refunds'];
                        $arr_refunds = array();
                        if (!empty($refunds)) {
                            foreach ($refunds as $k => $v) {
                                if (!empty($v['transactions'])) {
                                    foreach ($v['transactions'] as $kt => $vt) {
                                        $arr_refund['order_id'] = $order['id'];
                                        $arr_refund['refund_id'] = $vt['id'];
                                        $arr_refund['created_at'] = $vt['created_at'];
                                        //改变时间
                                        if (!empty($vt['created_at'])) {
                                            //直接截取获得时间戳
                                            $ycreated_at3 = str_replace('T', ' ', $vt['created_at']);
                                            $pos1 = strpos($ycreated_at3, '-');
                                            if($pos1 !== false){
                                                $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '-'));
                                            }
                                            $pos2 = strpos($ycreated_at3, '+');
                                            if($pos2 !== false){
                                                $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '+'));
                                            }
                                            
                                        }
                                        $arr_refund['processed_at'] = strtotime($ycreated_at3_new);
                                        $arr_refund['amount'] = $vt['amount'];
                                        $arr_refund['currency'] = $vt['currency'];
                                        $arr_refund['gateway'] = $vt['gateway'];
                                        $arr_refund['message'] = $vt['message'];
                                        $arr_refund['refund_status'] = $vt['status'];
                                        $arr_refund['refunds_key'] = $kt;
                                        $arr_refund['createtime'] = time();
                                        $arr_refund['site_id'] = $order['site_id'];
                                        $arr_refund['order_name'] = $order['name'];
                                        $arr_refunds[] = $arr_refund;
                                    }
                                }
                            }
                        }
                        if (!empty($arr_refunds)) {
                            table('order_refunds')
                                ->where('order_id', $order['id'])
                                ->delete();
                            table('order_refunds')->insertAll($arr_refunds);
                        }
                    }
                    //更新订单状态
                    if (!empty($data['order']['financial_status'])) {
                        //如果是退款的 部分退款的订单则不实时更新状态了
                        if ($data['order']['financial_status'] == DicOrder::$financial_status_refunded || $data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                            //也更新状态
                            $row['financial_status'] = $data['order']['financial_status'];
                        } else {
                            $row['financial_status'] = $data['order']['financial_status'];
                        }
                    } else {
                        $row['financial_status'] = DicOrder::$fulfillment_status_unfulfilled;;
                    }
                    //如果接口返回空 则改成未发货
                    if (!empty($data['order']['fulfillment_status'])) {
                        $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    } else {
                        $row['fulfillment_status'] = DicOrder::$fulfillment_status_unshipped;
                    }
                    //更新订单最新价格
                    $row['total_price'] = $data['order']['total_price'];
                    //部分退款计入金额
                    if ($data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                        $row['total_price'] = $data['order']['subtotal_price'];
                    }
                    //计算小费
                    if (!empty($data['order']['total_tip_received'])) {
                        $row['total_tip_received'] = $data['order']['total_tip_received'];
                    }

                    if (isset($data['order']['customer']['total_spent']) && $data['order']['customer']['total_spent'] > 0 && $data['order']['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                        $row['total_price'] = $data['order']['customer']['total_spent'];
                    }
                    if ($data['order']['financial_status'] == DicOrder::$financial_status_refunded) {
                        $row['total_price'] = 0;
                    }
                    //新增明细
                    if (isset($data['order']['current_subtotal_price'])) {
                        $row['current_subtotal_price'] = $data['order']['current_subtotal_price'];
                    } else {
                        $row['current_subtotal_price'] = 0;
                    }
                    // 可能是total_line_items_price
                    if (isset($data['order']['total_shipping_price_set']['shop_money']['amount'])) {
                        $row['total_shipping_price_set'] = $data['order']['total_shipping_price_set']['shop_money']['amount'];
                    } else {
                        $row['total_shipping_price_set'] = 0;
                    }

                    //联系人
                    if (isset($data['order']['customer']['email'])) {
                        $row['email'] = $data['order']['customer']['email'];
                    } else {
                        $row['email'] = '';
                    }

                    if (isset($data['order']['customer']['id'])) {
                        $row['customers_id'] = $data['order']['customer']['id'];
                    } else {
                        $row['customers_id'] = '';
                    }

                    if (isset($data['order']['shipping_address']['name'])) {
                        $row['shipping_name'] = $data['order']['shipping_address']['name'];
                    } else {
                        $row['shipping_name'] = '';
                    }
                    if (isset($data['order']['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "", $data['order']['shipping_address']['phone']);
                    } else {
                        $row['phone'] = '';
                    }
                    if (isset($data['order']['shipping_address']['province'])) {
                        $row['province'] = $data['order']['shipping_address']['province'];
                    } else {
                        $row['province'] = '';
                    }
                    if (isset($data['order']['shipping_address']['city'])) {
                        $row['city'] = $data['order']['shipping_address']['city'];
                    } else {
                        $row['city'] = '';
                    }
                    if (isset($data['order']['shipping_address']['zip'])) {
                        $row['zip'] = $data['order']['shipping_address']['zip'];
                    } else {
                        $row['zip'] = '';
                    }
                    if (isset($data['order']['shipping_address']['address1'])) {
                        $row['address1'] = $data['order']['shipping_address']['address1'];
                    } else {
                        $row['address1'] = '';
                    }
                    if (isset($data['order']['shipping_address']['country_code'])) {
                        $row['country_code'] = $data['order']['shipping_address']['country_code'];
                    } else {
                        $row['country_code'] = '';
                    }
                    if (isset($data['order']['order_status_url'])) {
                        $row['order_status_url'] = $data['order']['order_status_url'];
                    } else {
                        $row['order_status_url'] = '';
                    }
                    //note
                    $row['note'] = $data['order']['note'];
                    $row['closed_at'] = $data['order']['closed_at'];


                    if (!empty($data['order']['tags'])) {
                        $row['tags'] = $data['order']['tags'];
                    } else {
                        $row['tags'] = '暂无';
                    }

                    $row['referring_site'] = $data['order']['referring_site'];
                    $row['landing_site'] = $data['order']['landing_site'];
                    $row['current_total_discounts'] = $data['order']['current_total_discounts'];
                    $row['current_total_tax'] = $data['order']['current_total_tax'];
                    //referring_site是空且landing_site带/的不要，instagram facebook不要
                    //该订单当前归属人
                    // $wheregroup['createtime'] = array('elt', $row['created_at']);
                    // $wheregroup[''] = ['created_at', '<=', $row['created_at']];
                    // // $wheregroup['updatetime'] = array('egt', $row['created_at']);
                    // $wheregroup[''] = ['updatetime', '>=', $row['created_at']];
                    // table('site_group')
                    //     ->where('site_id', $site['id'])
                    //     ->where($wheregroup)
                    //     ->find();
                    // if (!empty($accounturlgroup)) {
                    //     $admin = table('admin')->where('id', $accounturlgroup['admin_id'])->find();
                    // }
                    //优先接口的标签
                    if (!empty($product_tagsz)) {
                        $row['user_id'] = $product_tagsz;
                        //再加店铺归属人
                        // if (!empty($admin) && $admin['id'] !== 1) {
                        //     $row['user_id'] = $row['user_id'].','.$admin['username'];
                        // }
                    } else {
                        //如果没有标签则用店铺归属人
                        // if (!empty($admin)) {
                        //     $row['user_id'] = $admin['username'];
                        // }else{
                        $row['user_id'] = 'Admin';
                        // }
                    }
                }
                $row['updateordertime'] = time();
                //同步物流消息
                //if (empty($row['tracking_number'])) {
                $order_fulfillments = table('order_fulfillments')->where('order_id', $order['id'])->find();
                if (!empty($order_fulfillments)) {
                    $row['tracking_number'] = $order_fulfillments['tracking_number'];
                    $row['tracking_company'] = $order_fulfillments['tracking_company'];
                    $order_fulfillments['order_id'] = $order['id'];
                } else {
                    $row['tracking_number'] = '';
                    $row['tracking_company'] = '';
                }
                //                }
                table('order')
                    ->where('id', $order['id'])
                    ->update($row);
                //更新交易
                // $this->update_order_transactions($order['id']);
            }
            return success('操作成功');
        } else {
            return  error('未找到相关订单');
        }
    }

    /**
     * 
     *  修改订单操作   
     *  type=2 更新最新修改订单
     *  type=3 更新之前修改订单
     */
    //TODO::定时任务的时间都为1分钟
    public function update_order()
    {
        $type = input('type');
        if (!$type) {
            return error('type不能为空');
        }
        $site_id = input('site_id');
        $where = [
            'site_type' => DicSite::$site_type_1,
            'status' => DicSite::$status_normal,
        ];
        if (!empty($site_id)) {
            $where['id'] = $site_id;
            $site = table('site')->where($where)->find();
        } else {
            $site = table('site')->where($where)->order(['updated_at_min' => 'asc'])->find();
        }
        $this->update_deal_orders($site, $type);
        return success('操作成功');
    }
    /**
     * 
     *  修改订单操作   
     *  type=2 更新最新修改订单
     *  type=3 更新之前修改订单
     */
    public function update_deal_orders($site, $type)
    {
        $url = $site['site_url'] . "/admin/api/2023-07/orders.json";
        if ($type == DicOrder::$type_2) {
            $last_order = table('order')
                ->where('site_id', $site['id'])
                ->order(['yupdated_at' => 'desc'])
                ->find();
            if (!empty($last_order['yupdated_at'])) {
                $updated_at_min = $last_order['yupdated_at'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min1 = date('Y-m-1', time());
                $updated_at_min2 = date('H:i:s', time());
                $updated_at_min = $updated_at_min1 . 'T' . $updated_at_min2 . '-04:00';
            }
            $url = $url . '?updated_at_min=' . $updated_at_min;
        }
        if ($type == DicOrder::$type_3) {
            if (!empty($site['updated_order'])) {
                $updated_at_max = $site['updated_order'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_max1 = date('Y-m-d', time());
                $updated_at_max2 = date('H:i:s', time());
                $updated_at_max = $updated_at_max1 . 'T' . $updated_at_max2 . '-04:00';
            }
            $url = $url . '?updated_at_max=' . $updated_at_max;
        }
        $url = $url . '&status=' . DicOrder::$status_any . '&limit=' . DicPublic::$task_limit_50 . '&financial_status=' . DicOrder::$financial_status_any;
        // halt($url);
        $data =  geturl($url, $site['apikey'], $site['apisecret']);
        // halt($data);
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return 2;
            }
            $orders = $data['orders'];
            if (is_array($orders) && !empty($orders)) {
                date_default_timezone_set('Asia/Shanghai');
                $update_ordertime_data['updated_order'] = 0;
                foreach ($orders as  $order) {
                    $row['yupdated_at'] = $order['updated_at'];
                    //订单更新时间
                    if (!empty($site['updated_order'])) {
                        $yupdated_atx = str_replace('T', ' ', $site['updated_order']);
                        $pos1 = strpos($yupdated_atx, '-');
                        if($pos1 !== false){
                            $yupdated_atx_new = substr($yupdated_atx, 0, strripos($yupdated_atx, '-'));
                        }
                        $pos2 = strpos($yupdated_atx, '+');
                        if($pos2 !== false){
                            $yupdated_atx_new = substr($yupdated_atx, 0, strripos($yupdated_atx, '+'));
                        }
                        
                        $yupdated_atx = strtotime($yupdated_atx_new);
                        //直接截取获得时间戳
                        $yupdated_at2 = str_replace('T', ' ', $order['updated_at']);
                        $pos1 = strpos($yupdated_at2, '-');
                        if($pos1 !== false){
                            $row['updated_at'] = substr($yupdated_at2, 0, strripos($yupdated_at2, '-'));
                        }
                        $pos2 = strpos($yupdated_at2, '+');
                        if($pos2 !== false){
                            $row['updated_at'] = substr($yupdated_at2, 0, strripos($yupdated_at2, '+'));
                        }
                        
                        $row['updated_at'] = strtotime($row['updated_at']);
                        if ($yupdated_atx > $row['updated_at']) {
                            if (!empty($zcreated_at)) {
                                if ($row['updated_at'] < $zcreated_at) {
                                    $zcreated_at = $row['updated_at'];
                                    $update_ordertime_data['updated_order'] = $row['yupdated_at'];
                                }
                            } else {
                                $zcreated_at = $row['updated_at'];
                                $update_ordertime_data['updated_order'] = $row['yupdated_at'];
                            }
                        } else {
                            $update_ordertime_data['updated_order'] = $site['updated_order'];
                        }
                    } else {
                        $update_ordertime_data['updated_order'] = $row['yupdated_at'];
                    }
                    //订单更新时间结束
                    $order_info = $this->model->where(['id' => $order['id']])->find();
                    if ($order_info) {
                        if ($order_info['yupdated_at'] < $order['updated_at']) {
                            //改变时间
                            if (!empty($order['created_at'])) {
                                //直接截取获得时间戳
                                $ycreated_at2 = str_replace('T', ' ', $order['created_at']);
                                $pos1 = strpos($ycreated_at2, '-');
                                if($pos1 !== false){
                                    $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                                }
                                $pos2 = strpos($ycreated_at2, '+');
                                if($pos2 !== false){
                                    $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                                }
                            }
                            $row['ycreated_at'] = $order['created_at'];
                            $row['yupdated_at'] = $order['updated_at'];
                            $row['created_at'] = strtotime($row['created_at']);
                            //新增商品物流单
                            if (isset($data['order']['fulfillments'])) {
                                $fulfillments = $data['order']['fulfillments'];
                                if (!empty($fulfillments)) {
                                    foreach ($fulfillments as $line_item) {
                                        $row['tracking_number'] = $line_item['tracking_number'];
                                        //如果有单号说明发货了
                                        if (!empty($row['tracking_number'])) {
                                            $ycreated_at2 = str_replace('T', ' ', $line_item['created_at']);
                                            $pos1 = strpos($ycreated_at2, '-');
                                            if($pos1 !== false){
                                                $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                                            }
                                            $pos2 = strpos($ycreated_at2, '+');
                                            if($pos2 !== false){
                                                $ycreated_at2_new = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                                            }
                                            
                                            $row['tracking_time'] = strtotime($ycreated_at2_new);
                                        }
                                    }
                                }
                            }
                            //新增退款信息
                            if (isset($order['refunds'])) {
                                $refunds = $order['refunds'];
                                $arr_refunds = array();
                                if (!empty($refunds)) {
                                    foreach ($refunds as $k => $v) {
                                        if (!empty($v['transactions'])) {
                                            foreach ($v['transactions'] as $kt => $vt) {
                                                $arr_refund['order_id'] = $order['id'];
                                                $arr_refund['refund_id'] = $vt['id'];
                                                $arr_refund['created_at'] = $vt['created_at'];
                                                //改变时间
                                                if (!empty($vt['created_at'])) {
                                                    //直接截取获得时间戳
                                                    $ycreated_at3 = str_replace('T', ' ', $vt['created_at']);
                                                    $pos1 = strpos($ycreated_at3, '-');
                                                    if($pos1 !== false){
                                                        $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '-'));
                                                    }
                                                    $pos2 = strpos($ycreated_at3, '+');
                                                    if($pos2 !== false){
                                                        $ycreated_at3_new = substr($ycreated_at3, 0, strripos($ycreated_at3, '+'));
                                                    }
                                                    
                                                }
                                                $arr_refund['processed_at'] = strtotime($ycreated_at3_new);
                                                $arr_refund['amount'] = $vt['amount'];
                                                $arr_refund['currency'] = $vt['currency'];
                                                $arr_refund['gateway'] = $vt['gateway'];
                                                $arr_refund['message'] = $vt['message'];
                                                $arr_refund['refund_status'] = $vt['status'];
                                                $arr_refund['refunds_key'] = $kt;
                                                $arr_refund['createtime'] = time();
                                                $arr_refund['site_id'] = $site['id'];
                                                $arr_refund['order_name'] = $order['name'];
                                                $arr_refunds[] = $arr_refund;
                                            }
                                        }
                                    }
                                }
                                if (!empty($arr_refunds)) {
                                    table('order_refunds')
                                        ->where('order_id', $order['id'])
                                        ->delete();
                                    table('order_refunds')->insertAll($arr_refunds);
                                }
                            }
                            //更新订单状态
                            if (!empty($order['financial_status'])) {
                                //如果是退款的 部分退款的订单则不实时更新状态了
                                if ($order['financial_status'] == DicOrder::$financial_status_refunded || $order['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                                    //也更新状态
                                    $row['financial_status'] = $order['financial_status'];
                                } else {
                                    $row['financial_status'] = $order['financial_status'];
                                }
                            } else {
                                $row['financial_status'] = DicOrder::$fulfillment_status_unfulfilled;;
                            }
                            //如果接口返回空 则改成未发货
                            if (!empty($data['order']['fulfillment_status'])) {
                                $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                            }
                            //更新订单最新价格
                            $row['total_price'] = $order['total_price'];
                            //计算小费
                            if (!empty($order['total_tip_received'])) {
                                $row['total_tip_received'] = $order['total_tip_received'];
                            }

                            if (isset($order['customer']['total_spent']) && $order['customer']['total_spent'] > 0 && $order['financial_status'] == DicOrder::$financial_status_partially_refunded) {
                                $row['total_price'] = $order['customer']['total_spent'];
                            }
                            if ($order['financial_status'] == DicOrder::$financial_status_refunded) {
                                $row['total_price'] = 0;
                            }
                            //新增明细
                            if (isset($order['current_subtotal_price'])) {
                                $row['current_subtotal_price'] = $order['current_subtotal_price'];
                            } else {
                                $row['current_subtotal_price'] = 0;
                            }
                            // 可能是total_line_items_price
                            if (isset($order['total_shipping_price_set']['shop_money']['amount'])) {
                                $row['total_shipping_price_set'] = $order['total_shipping_price_set']['shop_money']['amount'];
                            } else {
                                $row['total_shipping_price_set'] = 0;
                            }

                            $row['closed_at'] = $order['closed_at'];

                            table('order')
                                ->where('id', $order['id'])
                                ->update($row);
                            //更新交易
                            // $this->update_order_transactions($order['id']);
                        }
                    } else {
                        $arr['id'] = $order['id'];
                        $arr['name'] = $order['name'];
                        $arr['number'] = $order['number'];
                        $arr['order_number'] = $order['order_number'];
                        $arr['ycreated_at'] = $order['created_at'];
                        $arr['yupdated_at'] = $order['updated_at'];
                        //改变时间
                        if (!empty($arr['ycreated_at'])) {
                            //直接截取获得时间戳
                            $ycreated_at2 = str_replace('T', ' ', $arr['ycreated_at']);
                            $pos1 = strpos($ycreated_at2, '-');
                            if($pos1 !== false){
                                $arr['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                            }
                            $pos2 = strpos($ycreated_at2, '+');
                            if($pos2 !== false){
                                $arr['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '+'));
                            }
                            
                        }
                        $arr['created_at'] = strtotime($arr['created_at']);
                        //货币
                        $arr['currency'] = $order['currency'];
                        //支付状态
                        if (!empty($order['financial_status'])) {
                            $arr['financial_status'] = $order['financial_status'];
                        } else {
                            //自定义授权未完成
                            $arr['financial_status'] = DicOrder::$financial_status_unfulfilled;
                        }
                        $arr['ytotal_price'] = $order['total_price'];
                        $arr['total_price'] = $order['total_price'];
                        //顾客总花费
                        if (isset($order['customer']['total_spent']) && $order['total_price'] == 0) {
                            $arr['total_price'] = $order['customer']['total_spent'];
                        }
                        if ($arr['financial_status'] == DicOrder::$financial_status_refunded) {
                            $arr['total_price'] = 0;
                        }
                        $arr['site_id'] = $site['id'];
                        //支付方式
                        if (!empty($order['payment_gateway_names'][0]) && isset($order['payment_gateway_names'][0])) {
                            $arr['gateway'] = $order['payment_gateway_names'][0];
                        }
                        //如果接口返回空 则改成未发货
                        if (!empty($order['fulfillment_status'])) {
                            $arr['fulfillment_status'] = $order['fulfillment_status'];
                        } else {
                            $arr['fulfillment_status'] = DicOrder::$fulfillment_status_unshipped;
                        }

                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $this->model->insert($arr);
                    }
                }
            }
        }
        $update_ordertime_data['updated_at_min'] = time();
        table('site')
            ->where('id', $site['id'])
            ->update($update_ordertime_data);
        return 1;
    }

    //sku详情统计
    public function  order_count()
    {
        //前三天后三天时间筛选   单件加数量，多件不加
        $start_time =   time() - 8 * 24 * 3600;
        $end_time =  time() + 3 * 24 * 3600;
        $sql = "SELECT 
        a.total_price,
        a.created_at as create_time,
        a.fulfillment_status,
        a.site_id,
        c.sku,
        b.order_id
        FROM qu_order as a
        LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
        LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
        WHERE a.created_at >= " . $start_time . "
        AND a.created_at <= " . $end_time . "
        ORDER BY  create_time ASC";
        $join_datas = Db::query($sql);
        foreach ($join_datas as $item) {
            if (!empty($item['sku'])) {
                //-切割
                unset($sku_detail);
                $sku_detail =
                    [
                        'order_number' => $item['order_id'],
                        'order_money' => $item['total_price'],
                        'order_time' => $item['create_time'],
                        'delivery_status' => !empty($item['fulfillment_status']) ? $item['fulfillment_status'] : '',
                        'site' => $item['site_id'],
                        'sku' => $item['sku'],
                        'size' => '',
                        'color' => '',
                    ];
                $explode_arr = explode('-', $item['sku']);
                if (isset($explode_arr[1])) {
                    if (isset($explode_arr[0])) {
                        $sku_detail['brand'] = $explode_arr[0];
                    }
                    if (isset($explode_arr[2])) {
                        $sku_detail['size'] = $explode_arr[2];
                    }
                    if (isset($explode_arr[3])) {
                        $sku_detail['num'] = $explode_arr[3];
                    }
                    // +号切割循环处理订单
                    $explode_sku = explode('+', $explode_arr[1]);
                    foreach ($explode_sku  as   $sku_item) {
                        $sku_detail['color'] = $sku_item;
                        //通过订单id查询记录 没有就插入
                        $sku_detail_info = table('skucountdetail')->where(['order_number' => $item['order_id'], 'color' => $sku_item, 'size' => $sku_detail['size']])->find();
                        if (empty($sku_detail_info)) {
                            table('skucountdetail')->insert($sku_detail);
                        }
                    }
                }
            }
        }
        return  success('操作成功', '');
    }


    //通过订单号更改物流状态
    public function  update_order_count()
    {
        //前三天后三天时间筛选   单件加数量，多件不加
        $start_time =   time() - 8 * 24 * 3600;
        $end_time =  time() + 3 * 24 * 3600;
        //查询订单详情中的数据，更新物流状态
        $where[] = ['order_time', '>=', $start_time];
        $where[] = ['order_time', '<=', $end_time];
        $sku_detail = table('skucountdetail')->where($where)->select()->toarray();
        foreach ($sku_detail as $item) {
            //通过订单号查询订单表中的数据，并更新物流状态
            $order_info  = table('order')->field('fulfillment_status')->where(['id' => $item['order_number']])->find();
            if (!empty($order_info)) {
                //更新物流信息
                table('skucountdetail')->where(['order_number' => $item['order_number']])->update(['delivery_status' => $order_info['fulfillment_status']]);
            }
        }
        return  success('操作成功', '');
    }


    /**
     *每分钟执行----更新订单交易
     */
    public function update_order_transactions($id = null)
    {
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $order_id = input('order_id');
            $where = array();
            if (!empty($order_id)) {
                $where['id'] = $order_id;
            }
            $orders = table('order')
                ->order('transactions_time asc')
                ->where($where)
                ->limit('50')
                ->select()->toarray();
        }
        // halt($orders);
        if (!empty($orders)) {
            $row = array();
            foreach ($orders as $order) {
                $site = table('site')
                    ->where('id', $order['site_id'])
                    ->find();
                if (empty($site)) {
                    $row_c['transactions_time'] = time();
                    table('order')
                        ->where('id', $order['id'])
                        ->update($row_c);
                    continue;
                }
                $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $order['id'] . "/transactions.json";
                $data = geturl($url, $site['apikey'], $site['apisecret']);
                $data = json_decode($data, true);
                // halt($data);
                if (isset($data['transactions']) && !empty($data['transactions'])) {
                    $transactions = $data['transactions'];

                    table('order_transactions')
                        ->where('order_id', $order['id'])
                        ->delete();

                    foreach ($transactions as $k => $v) {
                        $row = array();
                        $row['createtime'] = $v['created_at'];
                        $row['kind'] = $v['kind'];
                        $row['update_time'] = $v['processed_at'];
                        $row['status'] = $v['status'];
                        $row['order_id'] = $v['order_id'];
                        $row['gateway'] = $v['gateway'];
                        $row['message'] = $v['message'];
                        $row['created_at'] = $v['created_at'];
                        $row['authorization'] = $v['authorization'];
                        $row['amount'] = $v['amount'];
                        $row['currency'] = $v['currency'];
                        if (isset($v['payment_id'])) {
                            $row['payment_id'] = $v['payment_id'];
                        }
                        // $transactions_info = table('order_transactions')
                        //     ->where('transactions_id', $v['id'])
                        //     ->find();
                        // if (empty($transactions_info)) {
                        $row['transactions_id'] = $v['id'];
                        table('order_transactions')->insert($row);
                        // }else{
                        //     $transactions_info = table('order_transactions')
                        //     ->where('transactions_id', $v['id'])
                        //     ->update($row);
                        // }
                    }
                }
                $arr['transactions_time'] = time();
                table('order')
                    ->where('id', $order['id'])
                    ->update($arr);
            }
            return success('操作成功');
        } else {
            return error('未找到相关订单');
        }
    }

    /**
     * 方法详情
     * @param array params
     */
    public function shopify_personreport_month($id = null)
    {
        if (empty($id)) {
            $id = input('admin_id');
        }
        $where = array();
        if (empty($id)) {
            $admin =  table('system_group_admin')
                ->where('group_id', 5)
                ->order('updatetime asc')
                ->find();
            $id = $admin['admin_id'];
        }
        $where['admin_id'] = $id;
        // $time = time() - 3600*24*77;
        // $wheregroup[] = ['updatetime', '>=', $time];
        $site_log =  table('site_log')
            ->where($where)
            // ->where($wheregroup)
            ->select()->toarray();
        if (!empty($site_log)) {
            table('shopify_personreport_day')
                ->where('admin_id', $id)
                ->delete();
            foreach ($site_log as $k => $v) {
                if ($v['type'] == '副运营') {
                    $wheretag = "AND tags like '%" . $v['label'] . "%'";
                    $sql = "
                    select 
                    sum(countnum) as count,
                    DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as timedate,
                    cast(sum(total_price) AS decimal(15,3)) as total_price,
                    cast(sum(current_total_tax) AS decimal(15,3)) as current_total_tax,
                    cast(sum(current_total_discounts) AS decimal(15,3)) as current_total_discounts,
                    cast(sum(current_subtotal_price) AS decimal(15,3)) as current_subtotal_price,
                    cast(sum(total_shipping_price_set) AS decimal(15,3)) as total_shipping_price_set,
                    cast(sum(total_tip_received) AS decimal(15,3)) as total_tip_received,
                    cast(sum(freight) AS decimal(15,3)) as freight,
                    cast(sum(material) AS decimal(15,3)) as material,
                    site_id,
                    currency
                    from qu_order 
                    WHERE 
                    site_id = " . $v['site_id'] . "
                    AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
                    " . $wheretag . "
                    AND created_at >= " . $v['createtime'] . "
                    AND created_at <= " . $v['updatetime'] . "
                    group by timedate
                    ORDER BY timedate DESC";
                    $join_datas = Db::query($sql);
                    foreach ($join_datas as $item) {
                        $item['time_stamp'] = strtotime($item['timedate']);
                        $item['label'] = $v['label'];
                        $item['admin_id'] = $id;
                        $item['label_type'] = 2; //副运营
                        table('shopify_personreport_day')
                            ->insert($item);
                    }
                }
                if ($v['type'] == '主运营') {
                    $sql = "
                    select 
                    sum(countnum) as count,
                    DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as timedate,
                    cast(sum(total_price) AS decimal(15,3)) as total_price,
                    cast(sum(current_total_tax) AS decimal(15,3)) as current_total_tax,
                    cast(sum(current_total_discounts) AS decimal(15,3)) as current_total_discounts,
                    cast(sum(current_subtotal_price) AS decimal(15,3)) as current_subtotal_price,
                    cast(sum(total_shipping_price_set) AS decimal(15,3)) as total_shipping_price_set,
                    cast(sum(total_tip_received) AS decimal(15,3)) as total_tip_received,
                    cast(sum(freight) AS decimal(15,3)) as freight,
                    cast(sum(material) AS decimal(15,3)) as material,
                    site_id,
                    currency
                    from qu_order 
                    WHERE 
                    site_id = " . $v['site_id'] . "
                    AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
                    AND created_at >= " . $v['createtime'] . "
                    AND created_at <= " . $v['updatetime'] . "
                    group by timedate
                    ORDER BY timedate DESC";
                    $join_datas = Db::query($sql);
                    foreach ($join_datas as $item) {
                        $item['time_stamp'] = strtotime($item['timedate']);
                        $item['label'] = '主运营';
                        $item['admin_id'] = $id;
                        // halt($item['timedate']);
                        $f_total_price = table('shopify_personreport_day')
                            ->field('sum(count) as count,sum(total_price) as total_price,sum(freight) as freight,sum(material) as material')
                            ->where('time_stamp', $item['time_stamp'])
                            ->where('site_id', $v['site_id'])
                            ->where('label_type', 2)
                            ->find();
                        if (!empty($f_total_price['total_price'])) {
                            $item['total_price'] = (float)number_format((float)$item['total_price'] - (float)$f_total_price['total_price'], 2, '.', '');
                        }
                        if (!empty($f_total_price['freight'])) {
                            $item['freight'] = (float)number_format((float)$item['freight'] - (float)$f_total_price['freight'], 2, '.', '');
                        }
                        if (!empty($f_total_price['count'])) {
                            $item['count'] = (int)$item['count'] - (int)$f_total_price['count'];
                        }
                        if (!empty($f_total_price['material'])) {
                            $item['material'] = (float)number_format((float)$item['material'] - (float)$f_total_price['material'], 2, '.', '');
                        }
                        $item['label_type'] = 1; //主运营
                        table('shopify_personreport_day')
                            ->insert($item);
                    }
                }
            }
        }
        $update['updatetime'] = time();
        $update = table('system_group_admin')
            ->where('admin_id', $id)
            ->update($update);
        return success('操作成功', $update);
    }

    /**
     * 运营每天的业绩
     * @param array params
     */
    public function shopify_personreport_day($id = null)
    {
        if (empty($id)) {
            $id = input('admin_id');
        }
        $where = array();
        if (empty($id)) {
            $admin =  table('system_group_admin')
                ->where('group_id', 5)
                ->order('updatetime_day asc')
                ->find();
            $id = $admin['admin_id'];
        }
        $where['admin_id'] = $id;
        $wheregroup[] = ['updatetime', '>=', time()];
        $site_log =  table('site_log')
            ->where($where)
            ->where($wheregroup)
            ->select()->toarray();
        if (!empty($site_log)) {
            $start_time = strtotime(date('Y-m-d 00:00:00', strtotime('-2 days')));
            foreach ($site_log as $k => $v) {
                if ($v['type'] == '副运营') {
                    $wheretag = "AND tags like '%" . $v['label'] . "%'";
                    $sql = "
                    select 
                    sum(countnum) as count,
                    DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as timedate,
                    cast(sum(total_price) AS decimal(15,3)) as total_price,
                    cast(sum(current_total_tax) AS decimal(15,3)) as current_total_tax,
                    cast(sum(current_total_discounts) AS decimal(15,3)) as current_total_discounts,
                    cast(sum(current_subtotal_price) AS decimal(15,3)) as current_subtotal_price,
                    cast(sum(total_shipping_price_set) AS decimal(15,3)) as total_shipping_price_set,
                    cast(sum(total_tip_received) AS decimal(15,3)) as total_tip_received,
                    cast(sum(freight) AS decimal(15,3)) as freight,
                    cast(sum(material) AS decimal(15,3)) as material,
                    site_id,
                    currency
                    from qu_order 
                    WHERE 
                    site_id = " . $v['site_id'] . "
                    AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
                    " . $wheretag . "
                    AND created_at >= " . $start_time . "
                    AND created_at <= " . $v['updatetime'] . "
                    group by timedate
                    ORDER BY timedate DESC";
                    $join_datas = Db::query($sql);
                    table('shopify_personreport_day')
                        ->where('time_stamp', '>=', $start_time)
                        ->where('admin_id', $id)
                        ->where('label', $v['label'])
                        ->where('site_id', $v['site_id'])
                        ->delete();
                    foreach ($join_datas as $item) {
                        $item['time_stamp'] = strtotime($item['timedate']);
                        $item['label'] = $v['label'];
                        $item['admin_id'] = $id;
                        $item['label_type'] = 2; //副运营
                        table('shopify_personreport_day')
                            ->insert($item);
                    }
                }
                if ($v['type'] == '主运营') {
                    $sql = "
                    select 
                    sum(countnum) as count,
                    DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as timedate,
                    cast(sum(total_price) AS decimal(15,3)) as total_price,
                    cast(sum(current_total_tax) AS decimal(15,3)) as current_total_tax,
                    cast(sum(current_total_discounts) AS decimal(15,3)) as current_total_discounts,
                    cast(sum(current_subtotal_price) AS decimal(15,3)) as current_subtotal_price,
                    cast(sum(total_shipping_price_set) AS decimal(15,3)) as total_shipping_price_set,
                    cast(sum(total_tip_received) AS decimal(15,3)) as total_tip_received,
                    cast(sum(freight) AS decimal(15,3)) as freight,
                    cast(sum(material) AS decimal(15,3)) as material,
                    site_id,
                    currency
                    from qu_order 
                    WHERE 
                    site_id = " . $v['site_id'] . "
                    AND (financial_status = 'paid' or financial_status = 'partially_paid')
                    AND created_at >= " . $start_time . "
                    AND created_at <= " . $v['updatetime'] . "
                    group by timedate
                    ORDER BY timedate DESC";
                    $join_datas = Db::query($sql);
                    table('shopify_personreport_day')
                        ->where('time_stamp', '>=', $start_time)
                        ->where('admin_id', $id)
                        ->where('label', '主运营')
                        ->where('site_id', $v['site_id'])
                        ->delete();
                    foreach ($join_datas as $item) {
                        $item['time_stamp'] = strtotime($item['timedate']);
                        $item['label'] = '主运营';
                        $item['admin_id'] = $id;
                        $f_total_price = table('shopify_personreport_day')
                            ->field('sum(count) as count,sum(total_price) as total_price,sum(freight) as freight,sum(material) as material')
                            ->where('time_stamp', $item['time_stamp'])
                            ->where('site_id', $v['site_id'])
                            ->where('label_type', 2)
                            ->find();
                        if (!empty($f_total_price['total_price'])) {
                            $item['total_price'] = (float)number_format((float)$item['total_price'] - (float)$f_total_price['total_price'], 2, '.', '');
                        }
                        if (!empty($f_total_price['freight'])) {
                            $item['freight'] = (float)number_format((float)$item['freight'] - (float)$f_total_price['freight'], 2, '.', '');
                        }
                        if (!empty($f_total_price['count'])) {
                            $item['count'] = (int)$item['count'] - (int)$f_total_price['count'];
                        }
                        if (!empty($f_total_price['material'])) {
                            $item['material'] = (float)number_format((float)$item['material'] - (float)$f_total_price['material'], 2, '.', '');
                        }
                        $item['label_type'] = 1; //主运营
                        table('shopify_personreport_day')
                            ->insert($item);
                    }
                }
            }
        }
        $update['updatetime_day'] = time();
        $update = table('system_group_admin')
            ->where('admin_id', $id)
            ->update($update);
        return success('操作成功', $update);
    }
    /**
     *更新订单物流跟采购成本，计算毛利
     * istransfer 物流
     * 0未对接成功
     * 1对接成功
     * 2估算物流成功
     * 100重新更新
     */
    public function update_order_istransfer_3day($id = null)
    {
        $shopify = array();
        $where = array();
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_id = input('site_id');
            $type = input('type');
            if (empty($type)) {
                $type = 0;
            }
            if ($type <= 100) {
                $where2['istransfer'] = $type;
            }
            if (!empty($site_id)) {
                $where[] = ['site_id', '=', $site_id];
            }
            $b_time = strtotime('-77 days');
            $e_time = time();
            $where[] = ['created_at', '>=', 1714406400];
            $where[] = ['created_at', '<=', 1717171200];
            $where[] = ['freight', '=', 0];
            $where[] = ['tracking_number', '<>', ""];
            $where[] = ['site_id', '<>', 121];
            $where_total_price[] = ['financial_status', 'in', ['paid', 'refunded', 'partially_refunded', 'partially_paid']];
            $orders = table('order')
                ->order('transfertime asc,id desc')
                // ->where('id','5451097243900')
                ->where($where)
                ->where($where2)
                ->where($where_total_price)
                // ->count();
                ->limit('30')
                ->select()->toarray();
                // halt($orders);
        }
        if (!empty($orders)) {
            foreach ($orders as $item) {
                $shopify[] = $this->add_freight($item);
            }
        }
        return success('操作成功', $shopify);
    }

    /**
     *更新订单物流
     */
    public function add_freight($ordershopify)
    {
        $ordertransfer = array();
        if (!empty($ordershopify['tracking_number'])) {
            $ordertransfer = Db::name('order_logistics')->where('transfer_number', $ordershopify['tracking_number'])->find();
            if (!empty($ordertransfer)) {
                $update2['status'] = 'normal';
                $update2['updatetime'] = time();
                Db::name('order_logistics')->where('id', $ordertransfer['id'])->update($update2);
                $data['istransfer'] = 1;
            }
        }
        // 预估
        // if (empty($ordertransfer)) {
        //     $order_quantity = Db::name('order_quantity')->where('order_id', $ordershopify['id'])->find();
        //     $where[] = ['b.freight', '>=', 1];
        //     if (!empty($order_quantity['variant_id'])) {
        //         $sql = "SELECT 
        //             SUM(`freight`) as freight
        //             FROM qu_order_quantity as a
        //             LEFT JOIN qu_order as b ON b.id = a.order_id
        //             WHERE b.freight >= 1
        //             AND b.istransfer = 1
        //             AND a.variant_id = ".$order_quantity['variant_id'];
        //         // halt($sql);
        //         $join_datas = Db::query($sql);
        //         $sql2 = "SELECT 
        //             count(a.quantity) as count
        //             FROM qu_order_quantity as a
        //             LEFT JOIN qu_order as b ON b.id = a.order_id
        //             WHERE b.freight >= 1
        //             AND b.istransfer = 1
        //             AND a.variant_id = ".$order_quantity['variant_id'];
        //         $join_datas2 = Db::query($sql2);
        //         if(!empty($join_datas[0]['freight']) && !empty($join_datas2[0]['count'])){
        //             $ordertransfer_one = (float)number_format((float)$join_datas[0]['freight'] / (float)$join_datas2[0]['count'], 3, '.', '');
        //             $ordertransfer['freight'] = $ordertransfer_one;
        //         }
        //         $data['istransfer'] = 2;
        //     }
        // }
        $data['transfertime'] = time();
        if (!empty($ordertransfer)) {
            $data['freight'] = $ordertransfer['freight'];
        } else {
            //估算开始
            $data['istransfer'] = 2;
            $data['freight'] = '50';
        }
        // halt($data);
        $shopify = Db::name('order')->where('id', $ordershopify['id'])->update($data);
        return $shopify;
    }

    /**
     *更新订单物流跟采购成本，计算毛利
     * ismaterial 采购
     * 0未对接成功
     * 1对接成功
     * 2预估
     * 100重新更新
     */
    public function update_order_ismaterial_3day($id = null)
    {
        $shopify = array();
        $where = array();
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_id = input('site_id');
            $type = input('type');
            if (empty($type)) {
                $type = 0;
            }
            if ($type <= 100) {
                $where2['ismaterial'] = $type;
            }
            if (!empty($site_id)) {
                $where[] = ['site_id', '=', $site_id];
            }
            $b_time = strtotime('-80 days');
            $e_time = time();
            //修正
            $correct = input('correct');
            if ($correct == 1) {
                $b_time = time() - 3600*24*5;
                $e_time = time();
                $where2['ismaterial'] = 2;
            }

            $where[] = ['created_at', '>=', 1714406400];
            $where[] = ['created_at', '<=', 1717171200];
            
            $where_total_price[] = ['financial_status', 'in', ['paid', 'refunded', 'partially_refunded', 'partially_paid']];
            $orders = table('order')
                ->order('materialtime asc,id desc')
                ->where($where)
                ->where($where2)
                ->where($where_total_price)
                ->where("site_id","<>","121")
                // ->count();
                ->limit('100')
                ->select()->toarray();
                // halt($orders);
                
        }
        if (!empty($orders)) {
            foreach ($orders as $item) {
                $shopify[] = $this->add_material($item);
            }
        }
        return success('操作成功', $shopify);
    }

    /**
     *更新订单采购
     */
    public function add_material($order)
    {
        # TODO zSHOPLINE接入
        $order_quantity = table('order_quantity')
            ->where('order_id', $order['id'])
            ->group("variant_id")
            ->select()
            ->toarray();
        $material = 0;
        //新方法
        if (!empty($order_quantity)) {
            foreach ($order_quantity as $item) {
                if (!empty($item['sku'])) {
                    $skucost = table('procurement_sku')
                        ->where('sku', $item['sku'])
                        ->order('timedate desc')
                        ->find();
                    if (!empty($skucost)) {
                        $newmaterial = $skucost['zmaterial'] * $item['quantity'];
                        $material = $material + $newmaterial;
                    }
                }
            }
        }
        $data['material'] = $material;
        $data['materialtime'] = time();
        if (!empty($data['material'])) {
            $data['ismaterial'] = 1;
        }
        //新估算开始
        if (empty($material)) {
            if (!empty($order_quantity)) {
                foreach ($order_quantity as $item) {
                    if (!empty($item['sku'])) {
                        $sku0 = '';
                        $pos = strpos($item['sku'], '-');
                        if($pos !== false){
                            $sku = explode('-',$item['sku']);
                            $sku0 = $sku[0];
                        }
                        if(!empty($sku0)){
                            $skucost = table('procurement_cost_last')
                                ->where('number', $sku0)
                                ->order('add_time desc')
                                ->find();
                            if (!empty($skucost)) {
                                $newmaterial = $skucost['material'] * $item['quantity'];
                                $material = $material + $newmaterial;
                            }
                        }
                    }
                }
            }
            $data['material'] = $material;
            $data['ismaterial'] = 2;
        }
        //估算开始
        // if (empty($material)) {
        //     if (!empty($order_quantity)) {
        //         foreach ($order_quantity as $item) {
        //             $newmaterial = 17.700 * $item['quantity'];
        //             $material = $material + $newmaterial;
        //             $material = 0;
        //         }
        //     }else{
        //         $material = 0;
        //     }
        //     $data['material'] = $material;
        //     $data['ismaterial'] = 2;
        // }
        $shopify = table('order')->where('id', $order['id'])->update($data);
        return $shopify;
    }

    /**
     * 方法详情
     * @param array params
     */
    public function test()
    {
        $order_test = table('order_test')->limit(50)->order('time asc')->select()->toarray();
        // halt($order_test);
        foreach ($order_test as $k => $v) {
            $order = table('order')->where('site_id', 10)->where('email', $v['email'])->find();
            if (!empty($order)) {
                $update['type'] = $order['name'];
                $update['site_id'] = $order['site_id'];
            } else {
                $order = table('order')->where('site_id', 10)->where('shipping_name', $v['name'])->find();
                if (!empty($order)) {
                    $update['type'] = $order['name'];
                    $update['site_id'] = $order['site_id'];
                } else {
                    //2
                    $order = table('order')->where('email', $v['email'])->find();
                    if (!empty($order)) {
                        $update['type'] = $order['name'];
                        $update['site_id'] = $order['site_id'];
                    } else {
                        $order = table('order')->where('shipping_name', $v['name'])->find();
                        if (!empty($order)) {
                            $update['type'] = $order['name'];
                            $update['site_id'] = $order['site_id'];
                        }
                    }
                }
            }
            $update['time'] = time();
            table('order_test')->where('id', $v['id'])->update($update);
        }
        return success('操作成功');
    }

    /**
     * 重复的商品详情
     * @param array params
     */
    public function test2()
    {
        $zhang_test =
            table('zhang_test')
            ->limit(50)
            ->select()
            ->toarray();
        if (!empty($zhang_test)) {
            foreach ($zhang_test as $k => $v) {
                $quantity = table('order_quantity')
                    ->where('product_id', $v['b'])
                    ->where('order_id', $v['c'])
                    ->where('variant_id', $v['d'])
                    ->find();
                $return = table('order_quantity')->where('id', $quantity['id'])->delete();
                if (!empty($return)) {
                    table('zhang_test')->where('id', $v['id'])->delete();
                }
            }
        }
        return success('操作成功');
    }

    //自动更新采购成本
    /**
     * 方法详情
     * @param array params
     */
    public function querypurchase()
    {
        $thismonth = date('m');
        $thisyear = date('Y');
        if ($thismonth == 1) {
            $lastmonth = 11;
            $lastyear = $thisyear - 1;
        } elseif ($thismonth == 2) {
            $lastmonth = 12;
            $lastyear = $thisyear - 1;
        } else {
            $lastmonth = $thismonth - 2;
            $lastyear = $thisyear;
        }
        $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
        $lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay)) . ' 23:59:59';
        $start_time = strtotime($lastStartDay);
        $end_time = strtotime($lastEndDay);
        $where_shopify[] = ['b.financial_status', 'in', ['paid', 'refunded', 'partially_refunded', 'partially_paid']];
        $where_shopify[] = ['b.ismaterial', '=', 2];
        $where_shopify[] =  ['b.created_at', 'between', [$start_time, $end_time]];
        $where2[]  = ['c.id', '>=', 7];
        $where2[]  = ['a.product_id', '>=', 1];
        $lists = table('order_quantity')
            ->field("a.*,b.site_id,b.name as order_name")
            ->alias('a')
            ->join('qu_order b', 'b.id = a.order_id', 'left')
            ->join('qu_site c', 'b.site_id = c.id', 'left')
            ->where($where2)
            ->where($where_shopify)
            ->group('a.product_id')
            ->order('b.site_id', 'desc')
            ->order('a.product_id', 'desc')
            ->select()->toarray();
    }

    /**
     * sql处理
     * @param array params
     */
    public function test33()
    {
        $data['transfer'] = '六月稳速易';
        // $count = table('order_logistics')->where('transfer','1026')->update($data);
        // $count = table('order_logistics')->where('transfer','1013')->delete();
        // halt($count);
    }

    /**
     * 更新物流账单的状态
     * @param array params
     */
    public function update_order_logistics()
    {
        //更新每日汇总
        $row = Db::name('order_logistics')
            ->where('status', 'hidden')
            ->limit(20)
            ->order('updatetime asc')
            ->select()->toarray();
        if (!empty($row)) {
            foreach ($row as $v) {
                $order = Db::name('order')->where('tracking_number', $v['transfer_number'])->find();
                if (!empty($order)) {
                    $transfer['status'] = 'normal';
                    $data['freight'] = $v['freight'];
                    $data['istransfer'] = 1;
                    Db::name('order')->where('id', $order['id'])->update($data);
                }
                $transfer['updatetime'] = time();
                Db::name('order_logistics')
                    ->where('id', $v['id'])
                    ->update($transfer);
            }
            return success('已更新');
        } else {
            return success('已全部更新');
        }
    }

    /**
     * 更新争议账单的状态
     * @param array params
     */
    public function update_order_dispute1()
    {
        //更新每日汇总
        $row = Db::name('order_dispute_manual')
            ->where('status', 'hidden')
            ->limit(10)
            ->order('updatetime asc')
            ->select();
        if (!empty($row)) {
            foreach ($row as $v) {
                $order = Db::name('order')->where('tracking_number', $v['transfer_number'])->find();
                if (!empty($order)) {
                    $transfer['status'] = 'normal';
                    $data['dispute_status'] = 1;
                    $data['dispute_cost'] = $v['cost'];
                    Db::name('order')->where('id', $order['id'])->update($data);
                } else {
                    $order = Db::name('order')->where('email', $v['transfer_number'])->find();
                    if (!empty($order)) {
                        $transfer['status'] = 'normal';
                        $data['dispute_status'] = 1;
                        $data['dispute_cost'] = $v['cost'];
                        Db::name('order')->where('id', $order['id'])->update($data);
                    }else{
                        $order = Db::name('order_transactions')->where('payment_id', $v['transfer_number'])->find();
                        if (!empty($order)) {
                            $transfer['status'] = 'normal';
                            $data['dispute_status'] = 1;
                            $data['dispute_cost'] = $v['cost'];
                            Db::name('order')->where('id', $order['id'])->update($data);
                        }
                    }
                }
                $transfer['updatetime'] = time();
                Db::name('order_dispute_manual')
                    ->where('id', $v['id'])
                    ->update($transfer);
            }
            return success('已更新');
        } else {
            return success('已全部更新');
        }
    }

    /**
     * 更新争议账单接口的状态
     * @param array params
     */
    public function update_order_dispute2()
    {
        //更新每日汇总
        $row = Db::name('order_dispute')
            ->where('order_status', 'hidden')
            ->limit(10)
            ->order('order_update asc')
            ->select();
        if (!empty($row)) {
            foreach ($row as $v) {
                if (!empty($v['order_id'])) {
                    $order = Db::name('order')->where('id', $v['order_id'])->find();
                    if (!empty($order)) {
                        $transfer['order_status'] = 'normal';
                        $data['dispute_status'] = 1;
                        $data['dispute_cost'] = 0;
                        Db::name('order')->where('id', $order['id'])->update($data);
                    }
                }
                $transfer['order_update'] = time();
                Db::name('order_dispute')
                    ->where('id', $v['id'])
                    ->update($transfer);
            }
            return success('已更新');
        } else {
            return success('已全部更新');
        }
    }

    /**
     *
     * 更新新品标签
     * 每月计算新品业绩会用到
     * 先在qu_new_product表里填入数据再调用该接口
     */
    public function update_order_new_product()
    {
        $thismonth = date('m');
        $thisyear = date('Y');
        if ($thismonth == 1) {
            $lastmonth = 11;
            $lastyear = $thisyear - 1;
        } elseif ($thismonth == 2) {
            $lastmonth = 12;
            $lastyear = $thisyear - 1;
        } else {
            $lastmonth = $thismonth - 2;
            $lastyear = $thisyear;
        }
        $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
        $lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay)) . ' 23:59:59';
        $b_time = strtotime($lastStartDay); //上个月的月初时间戳
        $e_time = strtotime($lastEndDay); //上个月的月末时间戳

        $new_product = table('new_product')
            ->where('time', $b_time)
            ->select()->toarray();
        $join_datas = array();
        if (!empty($new_product)) {
            foreach ($new_product as $k => $v) {
                $sql = "
                    UPDATE qu_order as a  
                    LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
                    LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
                    LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
                    SET a.new_product = 'FBNEW'
                    where a.created_at >= " . $b_time . "
                    AND a.created_at <= " . $e_time . "
                    AND a.site_id = " . $v['site_id'] . "
                    AND (b.sku like '%" . $v['sku'] . "%' or c.sku like '%" . $v['sku'] . "%')
                ";
                $join_datas[] = Db::query($sql);
            }
        }
        return   success('操作成功', $join_datas);
    }

    /**
     * 方法详情
     * @param array params
     */
    public function test4()
    {
        $list = array();
        //六月lily店
        $sql = "
            select 
            created_at,
            site_id,
            name,
            total_price,
            freight,
            material,
            currency,
            gateway,
            financial_status,
            fulfillment_status,
            tags,
            dispute_status,
            dispute_cost
            from qu_order 
            WHERE 
            site_id = 10
            AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
            AND created_at >= 1685548800
            AND created_at <= 1688140799
            ORDER BY created_at DESC";
        $join_datas = Db::query($sql);
        if (!empty($join_datas)) {
            $site_log2 =  table('site_log')
                ->where('site_id', 10)
                ->where('type', '副运营')
                ->select()->toarray();
            foreach ($join_datas as $item) {
                if (!empty($site_log2)) {
                    foreach ($site_log2 as $klog => $vlog) {
                        $pos = strpos($item['tags'], $vlog['label']);
                        if ($pos !== false) {
                            //找到
                            unset($item);
                            break;
                        }
                    }
                }
                if (isset($item)) {
                    $pos = strpos($item['tags'], 'fb');
                    if ($pos !== false) {
                        unset($item);
                    } else {
                        $order_test = table('order')
                            ->where('name', $item['name'])
                            ->where('site_id', 10)
                            ->find();
                        if (!empty($order_test) && $order_test['tags'] !== '暂无') {
                            $order_quantity_test = table('order_quantity')
                                ->where('sku', 'LIKE', '%top01%')
                                ->where('order_id', $order_test['id'])
                                ->find();
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->where('sku', 'LIKE', '%bra01%')
                                    ->where('order_id', $order_test['id'])
                                    ->find();
                            }
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->where('sku', 'LIKE', '%bra63%')
                                    ->where('order_id', $order_test['id'])
                                    ->find();
                            }
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->alias('a')
                                    ->join('order_sku b', 'b.variants_id = a.variant_id', 'left')
                                    ->where(['a.order_id' => $order_test['id']])
                                    ->where('a.sku', 'LIKE', '%top01%')
                                    ->find();
                            }
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->alias('a')
                                    ->join('order_sku b', 'b.variants_id = a.variant_id', 'left')
                                    ->where(['a.order_id' => $order_test['id']])
                                    ->where('a.sku', 'LIKE', '%bra01%')
                                    ->find();
                            }
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->alias('a')
                                    ->join('order_sku b', 'b.variants_id = a.variant_id', 'left')
                                    ->where(['a.order_id' => $order_test['id']])
                                    ->where('a.sku', 'LIKE', '%bra63%')
                                    ->find();
                            }
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->alias('a')
                                    ->join('fedition_ordersku b', 'b.variants_id = a.variant_id', 'left')
                                    ->where(['a.order_id' => $order_test['id']])
                                    ->where('a.sku', 'LIKE', '%top01%')
                                    ->find();
                            }
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->alias('a')
                                    ->join('fedition_ordersku b', 'b.variants_id = a.variant_id', 'left')
                                    ->where(['a.order_id' => $order_test['id']])
                                    ->where('a.sku', 'LIKE', '%bra01%')
                                    ->find();
                            }
                            if (empty($order_quantity_test)) {
                                $order_quantity_test = table('order_quantity')
                                    ->alias('a')
                                    ->join('fedition_ordersku b', 'b.variants_id = a.variant_id', 'left')
                                    ->where(['a.order_id' => $order_test['id']])
                                    ->where('a.sku', 'LIKE', '%bra63%')
                                    ->find();
                            }
                        }
                        if (!empty($order_test)) {
                            $update_test = array();
                            if (!empty($order_quantity_test)) {
                                $update_test['tags'] = 'fb';
                                table('order')
                                    ->where('id', $order_test['id'])
                                    ->update($update_test);
                            } else {
                                $update_test['tags'] = '暂无';
                                $update_test['site_id'] = 1100;
                                table('order')
                                    ->where('id', $order_test['id'])
                                    ->update($update_test);
                            }
                        }
                        $list[] = $item;
                    }
                }
            }
        }
        halt($list);
    }


    //计算出当天的编号总单量
    public function  brand_count()
    {
        $start_time = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $end_time = time();
        $sql = "SELECT 
        c.sku,
        sum(b.quantity) as count,
        a.created_at,
        c.variants_id as SKUid
        FROM qu_order as a
        LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
        LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
        LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
        where a.financial_status = 'paid'
        AND a.created_at >= " . $start_time . "
        AND a.created_at <= " . $end_time . "
        AND c.id > 1
        GROUP BY SKUid
        ORDER BY count DESC
    ";
        $join_datas = Db::query($sql);
        if (!$join_datas) {
            return [];
        }
        foreach ($join_datas as $k => $value) {
            $explode_arr = explode('-', $value['sku']);
            $result[$k] =
                [
                    'brand' => !empty($explode_arr[0]) ? $explode_arr[0] : '',
                    'count' => !empty($value['count']) ? (int)$value['count'] : 0,
                    'counttime' => !empty($value['created_at']) ? date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'))) : '',
                ];
        }
        table('brandcount')->insertAll($result);
        return success('操作成功');
    }

    /**
     * 检查店铺是否正常
     */
    public function isnormal()
    {
        $site_id = input('site_id');
        $where = array();
        if (!empty($site_id)) {
            $where['id'] = $site_id;
        }
        $site = Db::name('site')
            ->where($where)
            ->where('site_type', 1)
            ->order('inspect_time asc')
            ->find();
        $result = array();
        if ($site) {
            $result = $this->store_isnormal($site);
        }
        return success('操作成功', $result);
    }

    public function store_isnormal($site)
    {
        $url = $site['site_url'] . "/admin/api/2023-07/shop.json";
        $data = geturl($url, $site['apikey'], $site['apisecret']);
        $result = array();
        $update_ordertime_data = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                if ($data['errors'] == 'Unavailable Shop') {
                    //如果门店不可用，则报警
                    $update_ordertime_data['status'] = 'unavailable';
                    $update_ordertime_data['inspect_time'] = time();
                    $result = table('site')
                        ->where('id', $site['id'])
                        ->update($update_ordertime_data);
                    return $result;
                }
            }else{
                if(isset($data['shop']['domain']) && !empty($data['shop']['domain'])){
                    $update_ordertime_data['site_number'] = $data['shop']['domain'];
                }
                $update_ordertime_data['status'] = 'normal';
                $update_ordertime_data['inspect_time'] = time();
                $result = table('site')
                    ->where('id', $site['id'])
                    ->update($update_ordertime_data);
                return $result;
            }
        }else{
            //如果门店不可用，则报警
            $update_ordertime_data['status'] = 'unavailable';
            $update_ordertime_data['inspect_time'] = time();
            $result = table('site')
                ->where('id', $site['id'])
                ->update($update_ordertime_data);
            return $result;
        }
    }

    /**
    * 检查店铺跟运营业绩
    * @param array http://erp.back.cn/admin/Taskorder/inspect_shop_operations
    */
    public function inspect_shop_operations()
    {
        $date = date('Y-m-d', time() - 15 * 3600 - 24 * 3600);
        $start_time = strtotime(date('Y-m-d 00:00:00', time() - 15 * 3600 - 24 * 3600));
        $end_time = strtotime(date('Y-m-d 00:00:00', $start_time + 24 * 3600));
        $where[]  = ['created_at', '>=', $start_time];
        $where[]  = ['created_at', '<=', $end_time];
        $where_total_price[] = ['financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid, DicOrder::$financial_status_partially_refunded, DicOrder::$financial_status_refunded]];
        //店铺销售额
        $shopify_sales = table('order')->field('site_id,sum(total_price) as total,sum(countnum) as count,currency,sum(freight) as freight,sum(material) as material')->where($where)->where($where_total_price)->group('site_id')->order('total desc')->select()->toarray(); //总销售额
        $msg = array();
        $msg[] = $date.'检查店铺跟运营业绩';
        $ztotal = 0;
        foreach ($shopify_sales as $k=>$v) {
            $msg[] = '';
            $msg[] = '';
            //运营业绩
            $where_day  = array();
            $where_day[]  = ['time_stamp', '>=', $start_time];
            $where_day[]  = ['time_stamp', '<', $end_time];
            $where_day[]  = ['site_id', '=', $v['site_id']];
            $shopify_sales_day = table('shopify_personreport_day')
                ->field('admin_id,sum(total_price) as total,sum(count) as counts,label,site_id,sum(freight) as freight,sum(material) as material')
                ->where($where_day)
                ->order('total desc')
                ->find();
            // ->group('admin_id')
            // ->select()
            // ->toarray();
            $ztotal = (float)number_format((float)$v['total'] + $ztotal, 3, '.', '');
            $site = table('site')->where(['id' => $v['site_id']])->find();
            //核对业绩
            if(empty($shopify_sales_day['total']) || empty($v['total'])){
                $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺存在无人运营('.$v['total'].'-----'.$shopify_sales_day['total'].')-----------------------------------------';
            }else{
                $price_difference = (int)number_format((float)$v['total'] - (float)$shopify_sales_day['total'], 3, '.', '');
                if($price_difference > 0){
                    $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺业绩'.$v['total'].'比运营'.$shopify_sales_day['total'].'更多（正在处理）-----------------------------------------';
                    $this->update_operations($v['site_id'],$end_time);
                }else if($price_difference < 0){
                    $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺业绩'.$v['total'].'比运营'.$shopify_sales_day['total'].'更少（正在处理）-----------------------------------------';
                    // halt($v);
                    $this->update_operations($v['site_id'],$end_time);
                    // $this->less_performance($v['site_id']);
                }else{
                    $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺暂无异常('.$v['total'].'-----'.$shopify_sales_day['total'].')';
                }
            }
            //核对物流费
            if(empty($shopify_sales_day['freight']) || empty($v['freight'])){
                $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺存在无人运营('.$v['freight'].'-----'.$shopify_sales_day['freight'].')-----------------------------------------';
            }else{
                $price_difference = (int)number_format((float)$v['freight'] - (float)$shopify_sales_day['freight'], 3, '.', '');
                if($price_difference > 0){
                    $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺物流费'.$v['freight'].'比运营'.$shopify_sales_day['freight'].'更多（正在处理）-----------------------------------------';
                }else if($price_difference < 0){
                    $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺物流费'.$v['freight'].'比运营'.$shopify_sales_day['freight'].'更少（正在处理）-----------------------------------------';
                }else{
                    $msg[] = $v['site_id'].'-'.$site['site_name'].'店铺物流费暂无异常('.$v['freight'].'-----'.$shopify_sales_day['freight'].')';
                }
            }
        }
        $msg[] = '不区分币种：总业绩('.$ztotal.')';
        halt($msg);
    }
    
    /**
    * 修改店铺
    * @param array params
    */
    public function update_operations($site_id,$end_time)
    {
        $wheregroup = array();
        $wheregroup[]  = ['updatetime', '>=', $end_time];
        $wheregroup['site_id'] = $site_id;
        $site_log = table('site_log')
            ->where($wheregroup)
            ->select()->toarray();
        $return = array();
        foreach ($site_log as $k=>$v) {
            $return[] = $this->shopify_personreport_operations($v);
        }
        return $return;
    }
    
    /**
     * 检查更新店铺
     * @param array params
     */
    public function shopify_personreport_operations($v)
    {
        table('shopify_personreport_day')
            ->where('admin_id', $v['admin_id'])
            ->delete();
        if ($v['type'] == '副运营') {
            $wheretag = "AND tags like '%" . $v['label'] . "%'";
            $sql = "
            select 
            sum(countnum) as count,
            DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as timedate,
            cast(sum(total_price) AS decimal(15,3)) as total_price,
            cast(sum(current_total_tax) AS decimal(15,3)) as current_total_tax,
            cast(sum(current_total_discounts) AS decimal(15,3)) as current_total_discounts,
            cast(sum(current_subtotal_price) AS decimal(15,3)) as current_subtotal_price,
            cast(sum(total_shipping_price_set) AS decimal(15,3)) as total_shipping_price_set,
            cast(sum(total_tip_received) AS decimal(15,3)) as total_tip_received,
            cast(sum(freight) AS decimal(15,3)) as freight,
            cast(sum(material) AS decimal(15,3)) as material,
            site_id,
            currency
            from qu_order 
            WHERE 
            site_id = " . $v['site_id'] . "
            AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
            " . $wheretag . "
            AND created_at >= " . $v['createtime'] . "
            AND created_at <= " . $v['updatetime'] . "
            group by timedate
            ORDER BY timedate DESC";
            $join_datas = Db::query($sql);
            // halt($join_datas);
            foreach ($join_datas as $item) {
                $item['time_stamp'] = strtotime($item['timedate']);
                $item['label'] = $v['label'];
                $item['admin_id'] = $v['admin_id'];
                $item['label_type'] = 2; //副运营
                table('shopify_personreport_day')
                    ->insert($item);
            }
        }
        if ($v['type'] == '主运营') {
            $sql = "
            select 
            sum(countnum) as count,
            DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as timedate,
            cast(sum(total_price) AS decimal(15,3)) as total_price,
            cast(sum(current_total_tax) AS decimal(15,3)) as current_total_tax,
            cast(sum(current_total_discounts) AS decimal(15,3)) as current_total_discounts,
            cast(sum(current_subtotal_price) AS decimal(15,3)) as current_subtotal_price,
            cast(sum(total_shipping_price_set) AS decimal(15,3)) as total_shipping_price_set,
            cast(sum(total_tip_received) AS decimal(15,3)) as total_tip_received,
            cast(sum(freight) AS decimal(15,3)) as freight,
            cast(sum(material) AS decimal(15,3)) as material,
            site_id,
            currency
            from qu_order 
            WHERE 
            site_id = " . $v['site_id'] . "
            AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
            AND created_at >= " . $v['createtime'] . "
            AND created_at <= " . $v['updatetime'] . "
            group by timedate
            ORDER BY timedate DESC";
            $join_datas = Db::query($sql);
            foreach ($join_datas as $item) {
                $item['time_stamp'] = strtotime($item['timedate']);
                $item['label'] = '主运营';
                $item['admin_id'] = $v['admin_id'];
                // halt($item['timedate']);
                $f_total_price = table('shopify_personreport_day')
                    ->field('sum(count) as count,sum(total_price) as total_price,sum(freight) as freight,sum(material) as material')
                    ->where('time_stamp', $item['time_stamp'])
                    ->where('site_id', $v['site_id'])
                    ->where('label_type', 2)
                    ->find();
                if (!empty($f_total_price['total_price'])) {
                    $item['total_price'] = (float)number_format((float)$item['total_price'] - (float)$f_total_price['total_price'], 2, '.', '');
                }
                if (!empty($f_total_price['freight'])) {
                    $item['freight'] = (float)number_format((float)$item['freight'] - (float)$f_total_price['freight'], 2, '.', '');
                }
                if (!empty($f_total_price['count'])) {
                    $item['count'] = (int)$item['count'] - (int)$f_total_price['count'];
                }
                if (!empty($f_total_price['material'])) {
                    $item['material'] = (float)number_format((float)$item['material'] - (float)$f_total_price['material'], 2, '.', '');
                }
                $item['label_type'] = 1; //主运营
                table('shopify_personreport_day')
                    ->insert($item);
            }
        }
        return 1;
    }

    /**
    * 业绩如果少了
    * @param array params
    */
    public function less_performance()
    {
    
    }

    /**
    * 修改订单标签
    * @param array params
    */
    public function order_shecurve()
    {
        $order_shecurve = table('customerj_handle')
            ->field('a.*')
            ->alias('a')
            ->join('qu_customerj_today b','b.time = a.remarks', 'left')
            ->where('a.type',0)
            ->where('b.status',1)
            ->order('a.time asc')
            ->limit(10)
            ->select()->toarray();
        if(!empty($order_shecurve)){
            foreach ($order_shecurve as $k=>$v) {
                $update = array();
                $update['order_shecurve'] = 1;
                $update['tags'] = $v['tags'];
                $return = table('order')
                    ->where('order_number',$v['number'])
                    ->where('site_id',121)
                    ->update($update);
                $update2 = array();
                if($return){
                    $update2['type'] = 1;
                }else{
                    $update2['type'] = 2;
                }
                $update2['time'] = time();
                table('customerj_handle')
                    ->where('id',$v['id'])
                    ->update($update2);
            }
            return success('完成');
        }else{
            return success('暂无数据');
        }
    }
    
    /**
    * 订单标签转移到shopify上
    * @param array params
    */
    public function order_shecurve2()
    {
        $order_shecurve = table('customerj_handle')
            ->field('a.*')
            ->alias('a')
            ->join('qu_customerj_today b','b.time = a.remarks', 'left')
            ->where('a.type',0)
            // ->where('b.status',1)
            ->order('a.time asc')
            ->limit(10)
            ->select()->toarray();
        if(!empty($order_shecurve)){
            foreach ($order_shecurve as $k=>$v) {
                $return = "";
                $site = table('site')
                    ->where('id', 121)
                    ->find();
                $order = table('order')
                    ->where('order_number',$v['number'])
                    ->where('site_id',121)
                    ->find();
                if(!empty($order)){
                    $post['order']['id'] = $order['id'];
                    $post['order']['tags'] = $v['tags'];
                    $url = $site['site_url'] . "/admin/api/2021-07/orders/" . $order['id'] . ".json";
                    $return = puturl($url, $post, $site);
                }else{
                    $return = "";
                }
                $update2 = array();
                if(!empty($return)){
                    $update2['type'] = 3;
                }else{
                    $update2['type'] = 4;
                }
                $update2['time'] = time();
                table('customerj_handle')
                    ->where('id',$v['id'])
                    ->update($update2);
            }
            return success('完成');
        }else{
            return success('暂无数据');
        }
    }
    
    //转移
    //  Taskorder/api_transfer?oldid=29&newid=116
    public function api_transfer()
    {
        $site_oldid = $this->request->request('oldid');
        $site_newid = $this->request->request('newid');
        $where  = array();
        $order = table('order')
            ->where($where)
            ->where('site_id', $site_oldid)
            ->where('transfer_status', 0)
            // ->where('id', 5157532762155)
            ->order('transfer_time asc')
            ->limit(5)
            ->select()->toarray();
        $returns = [];
        if (!empty($order)) {
            foreach ($order as $k=>$v) {
                $return = $this->transfers($v, $site_newid);
                $arr['transfer_time'] = time();
                $arr['transfer_status'] = $return;
                $returns[] = table('order')
                    ->where('id', $v['id'])
                    ->update($arr);
            }
        }
        return success('操作完成', $returns);
    }

    public function transfers($shopify, $params)
    {
        $msgs = 3;
        if (!empty($shopify)) {
            $site = table('site')
                ->where('id', $shopify['site_id'])
                ->find();
            $url = $site['site_url'] . "/admin/api/2023-10/orders/" . $shopify['id'] . ".json";
            $ldata =  geturl($url, $site['apikey'], $site['apisecret']);
            if ($ldata) {
                $ldata2 = json_decode($ldata, true);
                if (!empty($ldata2['errors'])) {
                    return 'A-'.$ldata2['errors'];
                }
                if (!empty($ldata2['order'])) {
                    $ldata2['order']['name'] = str_replace("#","",$ldata2['order']['name']);
                    $ldata2['order']['name'] = '#0'.$ldata2['order']['name'];
                    $ldata2['order']['po_number'] = 1;
                    if(empty($ldata2['order']['tags'])){
                        unset($ldata2['order']['tags']);
                    }
                    unset($ldata2['order']['source_name']);
                    if(isset($ldata2['order']['fulfillments'][0]) && !empty($ldata2['order']['fulfillments'][0])){
                        $old_fulfillments = $ldata2['order']['fulfillments'][0];
                        unset($ldata2['order']['fulfillments']);
                    }
                    $ldata2['order']['current_subtotal_price'] = (float)number_format($ldata2['order']['current_subtotal_price']*4, 3, '.', '');
                    $ldata2['order']['current_total_price'] = (float)number_format($ldata2['order']['current_total_price']*4, 3, '.', '');
                    $ldata2['order']['subtotal_price'] = (float)number_format($ldata2['order']['subtotal_price']*4, 3, '.', '');
                    $ldata2['order']['total_line_items_price'] = (float)number_format($ldata2['order']['total_line_items_price']*4, 3, '.', '');
                    $ldata2['order']['total_price'] = (float)number_format($ldata2['order']['total_price']*4, 3, '.', '');
                    if(isset($ldata2['order']['line_items'][0]['price']) && !empty($ldata2['order']['line_items'][0]['price'])){
                        $ldata2['order']['line_items'][0]['price'] = (float)number_format($ldata2['order']['line_items'][0]['price']*4, 3, '.', '');
                    }
                    if(isset($ldata2['order']['current_total_price_set']['shop_money']['amount']) && !empty($ldata2['order']['current_total_price_set']['shop_money']['amount'])){
                        $ldata2['order']['current_total_price_set']['shop_money']['amount'] = (float)number_format($ldata2['order']['current_total_price_set']['shop_money']['amount']*4, 3, '.', '');
                    }
                    if(isset($ldata2['order']['current_total_price_set']['presentment_money']['amount']) && !empty($ldata2['order']['current_total_price_set']['presentment_money']['amount'])){
                        $ldata2['order']['current_total_price_set']['presentment_money']['amount'] = (float)number_format($ldata2['order']['current_total_price_set']['presentment_money']['amount']*4, 3, '.', '');
                    }
                    if(isset($ldata2['order']['total_price_set']['shop_money']['amount']) && !empty($ldata2['order']['total_price_set']['shop_money']['amount'])){
                        $ldata2['order']['total_price_set']['shop_money']['amount'] = (float)number_format($ldata2['order']['total_price_set']['shop_money']['amount']*4, 3, '.', '');
                    }
                    if(isset($ldata2['order']['total_price_set']['presentment_money']['amount']) && !empty($ldata2['order']['total_price_set']['presentment_money']['amount'])){
                        $ldata2['order']['total_price_set']['presentment_money']['amount'] = (float)number_format($ldata2['order']['total_price_set']['presentment_money']['amount']*4, 3, '.', '');
                    }
                    $ldata2['order']['email'] = buildRandStr()."@eliabella.com";
                    $ldata2['order']['customer']['email'] = $ldata2['order']['email'];
                    $ldata2['order']['contact_email'] = $ldata2['order']['email'];
                    $ldata2['order']['line_items'][0]['name'] = "Woobilly Fashion Deep Cup Bra with shapewear incorporated (Size runs the same as regular bras)";
                    $ldata2['order']['line_items'][0]['title'] = "Woobilly Fashion Deep Cup Bra with shapewear incorporated (Size runs the same as regular bras)";
                    $ldata2['order']['line_items'][0]['product_id'] = "8099116122243";
                    unset($ldata2['order']['id']);
                    unset($ldata2['order']['admin_graphql_api_id']);
                    $site2 = table('site')
                        ->where('id', $params)
                        ->find();
                    $url2 = $site2['site_url'] . "/admin/api/2023-10/orders.json";
                    $newreturn = posturl($url2, $ldata2, $site2);
                    if(!empty($newreturn)){
                        return 3;
                    }
                }
            }
            return $msgs;
        } else {
            return 4;
        }
    }

    /**
     *
     */
    public function update_order_4months($id = null)
    {
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_ids = input('site_ids');
            $where = array();
            if (!empty($site_ids)) {
                $where['site_id'] = $site_ids;
            } else {
                //从7店铺开始更新
                // $where['site_id']  = array('egt', 7);
                $where[]  = ['site_id', '>=', 7];
            }
            // $where['created_at'] = array(array('egt', $b_time), array('elt', $e_time));
            // $where[] = ['created_at', '>=', $b_time];
            // $where[] = ['created_at', '<=', $e_time];
            $where[] = ['updateordertime', '=', 0];
            $orders = table('order')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('5')
                ->select()->toarray();
        }
        if (!empty($orders)) {
            $row = array();
            foreach ($orders as $order) {
                $site = table('site')
                    ->where('id', $order['site_id'])
                    ->find();
                if (empty($site)) {
                    $row_c['updateordertime'] = time();
                    table('order')
                        ->where('id', $order['id'])
                        ->update($row_c);
                    continue;
                }
                $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $order['id'] . ".json";
                $data = geturl($url, $site['apikey'], $site['apisecret']);
                $data = json_decode($data, true);
                $row = array();
                if (isset($data['order'])) {
                    $row['landing_site'] = $data['order']['landing_site'];
                }
                $row['updateordertime'] = time();
                //                }
                table('order')
                    ->where('id', $order['id'])
                    ->update($row);
            }
            return success('操作成功');
        } else {
            return error('未找到相关订单');
        }
    }

    
    /**
    * 去重
    * @param array params
    */
    public function ModifyDeduplication()
    {
        $lists = table('order')  
            ->field('a.id') // 只选择 order 表的 id  
            ->alias('a')  
            ->join('qu_customerjourneysummary c', 'c.order_id = a.id', 'left')  
            ->where('a.site_id', '121')  
            ->whereNull('c.order_id') // 使用 whereNull 来检查 null 值，这样更清晰  
            ->select()  
            ->toArray(); 
        foreach ($lists as $k=>$v) {
            if(!empty($v['id'])){
                $arr = array();
                $arr['order_id'] = $v['id'];
                table('customerjourneysummary')->insert($arr);
            }
        }
    }


    public function store_isreports()
    {
        $site = table('site')
            ->where('id', 121)
            ->find();
        $url = $site['site_url'] . "/admin/api/2023-07/reports.json";
        $data = geturl($url, $site['apikey'], $site['apisecret']);
        $data = json_decode($data, true);
        halt($data);
    }

    /**
     * 报表
     * @param array params
     */
    public function add_report()
    {
        $site = table('site')
            ->where('id', 121)
            ->find();
        $url = $site['site_url'] . "/admin/api/2023-07/reports.json";        

        $addreport['name'] = 'test report';
        $addreport['shopify_ql'] = 'SHOW total_sales BY order_id FROM sales SINCE -30d UNTIL today ORDER BY total_sales';
        $newdata['report'] = $addreport;

        $data = posturl($url, $newdata, $site);
        $data = json_decode($data, true);

        halt($data);
    }
    

}
